blob: 59ed9dfbc4a78f1e90d6c3ca59feeb8705399852 [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
5package main
6
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"
15 "encoding/asn1"
16 "errors"
17 "fmt"
18 "io"
David Benjamind30a9902014-08-24 01:44:23 -040019 "math/big"
Adam Langley95c29f32014-06-20 12:00:00 -070020)
21
22// serverHandshakeState contains details of a server handshake in progress.
23// It's discarded once the handshake has completed.
24type serverHandshakeState struct {
25 c *Conn
26 clientHello *clientHelloMsg
27 hello *serverHelloMsg
28 suite *cipherSuite
29 ellipticOk bool
30 ecdsaOk bool
31 sessionState *sessionState
32 finishedHash finishedHash
33 masterSecret []byte
34 certsFromClient [][]byte
35 cert *Certificate
David Benjamin83f90402015-01-27 01:09:43 -050036 finishedBytes []byte
Adam Langley95c29f32014-06-20 12:00:00 -070037}
38
39// serverHandshake performs a TLS handshake as a server.
40func (c *Conn) serverHandshake() error {
41 config := c.config
42
43 // If this is the first server handshake, we generate a random key to
44 // encrypt the tickets with.
45 config.serverInitOnce.Do(config.serverInit)
46
David Benjamin83c0bc92014-08-04 01:23:53 -040047 c.sendHandshakeSeq = 0
48 c.recvHandshakeSeq = 0
49
Adam Langley95c29f32014-06-20 12:00:00 -070050 hs := serverHandshakeState{
51 c: c,
52 }
53 isResume, err := hs.readClientHello()
54 if err != nil {
55 return err
56 }
57
58 // For an overview of TLS handshaking, see https://tools.ietf.org/html/rfc5246#section-7.3
59 if isResume {
60 // The client has included a session ticket and so we do an abbreviated handshake.
61 if err := hs.doResumeHandshake(); err != nil {
62 return err
63 }
64 if err := hs.establishKeys(); err != nil {
65 return err
66 }
David Benjaminbed9aae2014-08-07 19:13:38 -040067 if c.config.Bugs.RenewTicketOnResume {
68 if err := hs.sendSessionTicket(); err != nil {
69 return err
70 }
71 }
Adam Langley95c29f32014-06-20 12:00:00 -070072 if err := hs.sendFinished(); err != nil {
73 return err
74 }
David Benjamin83f90402015-01-27 01:09:43 -050075 // Most retransmits are triggered by a timeout, but the final
76 // leg of the handshake is retransmited upon re-receiving a
77 // Finished.
David Benjaminb3774b92015-01-31 17:16:01 -050078 if err := c.simulatePacketLoss(func() {
79 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
David Benjamina4e6d482015-03-02 19:10:53 -050080 c.dtlsFlushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -050081 }); err != nil {
David Benjamin83f90402015-01-27 01:09:43 -050082 return err
83 }
David Benjamind30a9902014-08-24 01:44:23 -040084 if err := hs.readFinished(isResume); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -070085 return err
86 }
87 c.didResume = true
88 } else {
89 // The client didn't include a session ticket, or it wasn't
90 // valid so we do a full handshake.
91 if err := hs.doFullHandshake(); err != nil {
92 return err
93 }
94 if err := hs.establishKeys(); err != nil {
95 return err
96 }
David Benjamind30a9902014-08-24 01:44:23 -040097 if err := hs.readFinished(isResume); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -070098 return err
99 }
David Benjamin1c633152015-04-02 20:19:11 -0400100 if c.config.Bugs.AlertBeforeFalseStartTest != 0 {
101 c.sendAlert(c.config.Bugs.AlertBeforeFalseStartTest)
102 }
David Benjamine58c4f52014-08-24 03:47:07 -0400103 if c.config.Bugs.ExpectFalseStart {
104 if err := c.readRecord(recordTypeApplicationData); err != nil {
David Benjamin1c633152015-04-02 20:19:11 -0400105 return fmt.Errorf("tls: peer did not false start: %s", err)
David Benjamine58c4f52014-08-24 03:47:07 -0400106 }
107 }
Adam Langley95c29f32014-06-20 12:00:00 -0700108 if err := hs.sendSessionTicket(); err != nil {
109 return err
110 }
111 if err := hs.sendFinished(); err != nil {
112 return err
113 }
114 }
115 c.handshakeComplete = true
David Benjaminc565ebb2015-04-03 04:06:36 -0400116 copy(c.clientRandom[:], hs.clientHello.random)
117 copy(c.serverRandom[:], hs.hello.random)
118 copy(c.masterSecret[:], hs.masterSecret)
Adam Langley95c29f32014-06-20 12:00:00 -0700119
120 return nil
121}
122
123// readClientHello reads a ClientHello message from the client and decides
124// whether we will perform session resumption.
125func (hs *serverHandshakeState) readClientHello() (isResume bool, err error) {
126 config := hs.c.config
127 c := hs.c
128
David Benjamin83f90402015-01-27 01:09:43 -0500129 if err := c.simulatePacketLoss(nil); err != nil {
130 return false, err
131 }
Adam Langley95c29f32014-06-20 12:00:00 -0700132 msg, err := c.readHandshake()
133 if err != nil {
134 return false, err
135 }
136 var ok bool
137 hs.clientHello, ok = msg.(*clientHelloMsg)
138 if !ok {
139 c.sendAlert(alertUnexpectedMessage)
140 return false, unexpectedMessageError(hs.clientHello, msg)
141 }
Feng Lu41aa3252014-11-21 22:47:56 -0800142 if config.Bugs.RequireFastradioPadding && len(hs.clientHello.raw) < 1000 {
143 return false, errors.New("tls: ClientHello record size should be larger than 1000 bytes when padding enabled.")
144 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400145
146 if c.isDTLS && !config.Bugs.SkipHelloVerifyRequest {
David Benjamin8bc38f52014-08-16 12:07:27 -0400147 // Per RFC 6347, the version field in HelloVerifyRequest SHOULD
148 // be always DTLS 1.0
David Benjamin83c0bc92014-08-04 01:23:53 -0400149 helloVerifyRequest := &helloVerifyRequestMsg{
David Benjamin8bc38f52014-08-16 12:07:27 -0400150 vers: VersionTLS10,
David Benjamin83c0bc92014-08-04 01:23:53 -0400151 cookie: make([]byte, 32),
152 }
153 if _, err := io.ReadFull(c.config.rand(), helloVerifyRequest.cookie); err != nil {
154 c.sendAlert(alertInternalError)
155 return false, errors.New("dtls: short read from Rand: " + err.Error())
156 }
157 c.writeRecord(recordTypeHandshake, helloVerifyRequest.marshal())
David Benjamina4e6d482015-03-02 19:10:53 -0500158 c.dtlsFlushHandshake()
David Benjamin83c0bc92014-08-04 01:23:53 -0400159
David Benjamin83f90402015-01-27 01:09:43 -0500160 if err := c.simulatePacketLoss(nil); err != nil {
161 return false, err
162 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400163 msg, err := c.readHandshake()
164 if err != nil {
165 return false, err
166 }
167 newClientHello, ok := msg.(*clientHelloMsg)
168 if !ok {
169 c.sendAlert(alertUnexpectedMessage)
170 return false, unexpectedMessageError(hs.clientHello, msg)
171 }
172 if !bytes.Equal(newClientHello.cookie, helloVerifyRequest.cookie) {
173 return false, errors.New("dtls: invalid cookie")
174 }
David Benjaminf2fedef2014-08-16 01:37:34 -0400175
176 // Apart from the cookie, the two ClientHellos must
177 // match. Note that clientHello.equal compares the
178 // serialization, so we make a copy.
179 oldClientHelloCopy := *hs.clientHello
180 oldClientHelloCopy.raw = nil
181 oldClientHelloCopy.cookie = nil
182 newClientHelloCopy := *newClientHello
183 newClientHelloCopy.raw = nil
184 newClientHelloCopy.cookie = nil
185 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400186 return false, errors.New("dtls: retransmitted ClientHello does not match")
187 }
188 hs.clientHello = newClientHello
189 }
190
David Benjaminc44b1df2014-11-23 12:11:01 -0500191 if config.Bugs.RequireSameRenegoClientVersion && c.clientVersion != 0 {
192 if c.clientVersion != hs.clientHello.vers {
193 return false, fmt.Errorf("tls: client offered different version on renego")
194 }
195 }
196 c.clientVersion = hs.clientHello.vers
197
David Benjamin6ae7f072015-01-26 10:22:13 -0500198 // Reject < 1.2 ClientHellos with signature_algorithms.
199 if c.clientVersion < VersionTLS12 && len(hs.clientHello.signatureAndHashes) > 0 {
200 return false, fmt.Errorf("tls: client included signature_algorithms before TLS 1.2")
201 }
David Benjamin72dc7832015-03-16 17:49:43 -0400202 if config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
203 hs.clientHello.signatureAndHashes = config.signatureAndHashesForServer()
204 }
David Benjamin6ae7f072015-01-26 10:22:13 -0500205
David Benjamin8bc38f52014-08-16 12:07:27 -0400206 c.vers, ok = config.mutualVersion(hs.clientHello.vers)
207 if !ok {
208 c.sendAlert(alertProtocolVersion)
209 return false, fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
210 }
Adam Langley95c29f32014-06-20 12:00:00 -0700211 c.haveVers = true
212
213 hs.hello = new(serverHelloMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400214 hs.hello.isDTLS = c.isDTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700215
216 supportedCurve := false
217 preferredCurves := config.curvePreferences()
David Benjaminc574f412015-04-20 11:13:01 -0400218 if config.Bugs.IgnorePeerCurvePreferences {
219 hs.clientHello.supportedCurves = preferredCurves
220 }
Adam Langley95c29f32014-06-20 12:00:00 -0700221Curves:
222 for _, curve := range hs.clientHello.supportedCurves {
223 for _, supported := range preferredCurves {
224 if supported == curve {
225 supportedCurve = true
226 break Curves
227 }
228 }
229 }
230
231 supportedPointFormat := false
232 for _, pointFormat := range hs.clientHello.supportedPoints {
233 if pointFormat == pointFormatUncompressed {
234 supportedPointFormat = true
235 break
236 }
237 }
238 hs.ellipticOk = supportedCurve && supportedPointFormat
239
240 foundCompression := false
241 // We only support null compression, so check that the client offered it.
242 for _, compression := range hs.clientHello.compressionMethods {
243 if compression == compressionNone {
244 foundCompression = true
245 break
246 }
247 }
248
249 if !foundCompression {
250 c.sendAlert(alertHandshakeFailure)
251 return false, errors.New("tls: client does not support uncompressed connections")
252 }
253
254 hs.hello.vers = c.vers
255 hs.hello.random = make([]byte, 32)
256 _, err = io.ReadFull(config.rand(), hs.hello.random)
257 if err != nil {
258 c.sendAlert(alertInternalError)
259 return false, err
260 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700261
Adam Langleycf2d4f42014-10-28 19:06:14 -0700262 if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) {
Adam Langley2ae77d22014-10-28 17:29:33 -0700263 c.sendAlert(alertHandshakeFailure)
Adam Langleycf2d4f42014-10-28 19:06:14 -0700264 return false, errors.New("tls: renegotiation mismatch")
Adam Langley2ae77d22014-10-28 17:29:33 -0700265 }
Adam Langleycf2d4f42014-10-28 19:06:14 -0700266
267 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
268 hs.hello.secureRenegotiation = append(hs.hello.secureRenegotiation, c.clientVerify...)
269 hs.hello.secureRenegotiation = append(hs.hello.secureRenegotiation, c.serverVerify...)
270 if c.config.Bugs.BadRenegotiationInfo {
271 hs.hello.secureRenegotiation[0] ^= 0x80
272 }
273 } else {
274 hs.hello.secureRenegotiation = hs.clientHello.secureRenegotiation
275 }
276
Adam Langley95c29f32014-06-20 12:00:00 -0700277 hs.hello.compressionMethod = compressionNone
David Benjamin35a7a442014-07-05 00:23:20 -0400278 hs.hello.duplicateExtension = c.config.Bugs.DuplicateExtension
Adam Langley95c29f32014-06-20 12:00:00 -0700279 if len(hs.clientHello.serverName) > 0 {
280 c.serverName = hs.clientHello.serverName
281 }
David Benjaminfa055a22014-09-15 16:51:51 -0400282
283 if len(hs.clientHello.alpnProtocols) > 0 {
284 if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
285 hs.hello.alpnProtocol = selectedProto
286 c.clientProtocol = selectedProto
David Benjaminfc7b0862014-09-06 13:21:53 -0400287 c.usedALPN = true
David Benjaminfa055a22014-09-15 16:51:51 -0400288 }
289 } else {
290 // Although sending an empty NPN extension is reasonable, Firefox has
291 // had a bug around this. Best to send nothing at all if
292 // config.NextProtos is empty. See
293 // https://code.google.com/p/go/issues/detail?id=5445.
294 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
295 hs.hello.nextProtoNeg = true
296 hs.hello.nextProtos = config.NextProtos
297 }
Adam Langley95c29f32014-06-20 12:00:00 -0700298 }
Adam Langley75712922014-10-10 16:23:43 -0700299 hs.hello.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !c.config.Bugs.NoExtendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700300
301 if len(config.Certificates) == 0 {
302 c.sendAlert(alertInternalError)
303 return false, errors.New("tls: no certificates configured")
304 }
305 hs.cert = &config.Certificates[0]
306 if len(hs.clientHello.serverName) > 0 {
307 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
308 }
David Benjamine78bfde2014-09-06 12:45:15 -0400309 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
310 return false, errors.New("tls: unexpected server name")
311 }
Adam Langley95c29f32014-06-20 12:00:00 -0700312
David Benjamind30a9902014-08-24 01:44:23 -0400313 if hs.clientHello.channelIDSupported && config.RequestChannelID {
314 hs.hello.channelIDRequested = true
315 }
316
David Benjaminca6c8262014-11-15 19:06:08 -0500317 if hs.clientHello.srtpProtectionProfiles != nil {
318 SRTPLoop:
319 for _, p1 := range c.config.SRTPProtectionProfiles {
320 for _, p2 := range hs.clientHello.srtpProtectionProfiles {
321 if p1 == p2 {
322 hs.hello.srtpProtectionProfile = p1
323 c.srtpProtectionProfile = p1
324 break SRTPLoop
325 }
326 }
327 }
328 }
329
330 if c.config.Bugs.SendSRTPProtectionProfile != 0 {
331 hs.hello.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
332 }
333
Adam Langley95c29f32014-06-20 12:00:00 -0700334 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
335
336 if hs.checkForResumption() {
337 return true, nil
338 }
339
Adam Langleyac61fa32014-06-23 12:03:11 -0700340 var scsvFound bool
341
342 for _, cipherSuite := range hs.clientHello.cipherSuites {
343 if cipherSuite == fallbackSCSV {
344 scsvFound = true
345 break
346 }
347 }
348
349 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
350 return false, errors.New("tls: no fallback SCSV found when expected")
351 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
352 return false, errors.New("tls: fallback SCSV found when not expected")
353 }
354
David Benjamin67d1fb52015-03-16 15:16:23 -0400355 if config.Bugs.IgnorePeerCipherPreferences {
356 hs.clientHello.cipherSuites = c.config.cipherSuites()
357 }
Adam Langley95c29f32014-06-20 12:00:00 -0700358 var preferenceList, supportedList []uint16
359 if c.config.PreferServerCipherSuites {
360 preferenceList = c.config.cipherSuites()
361 supportedList = hs.clientHello.cipherSuites
362 } else {
363 preferenceList = hs.clientHello.cipherSuites
364 supportedList = c.config.cipherSuites()
365 }
366
367 for _, id := range preferenceList {
368 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
369 break
370 }
371 }
372
373 if hs.suite == nil {
374 c.sendAlert(alertHandshakeFailure)
375 return false, errors.New("tls: no cipher suite supported by both client and server")
376 }
377
378 return false, nil
379}
380
381// checkForResumption returns true if we should perform resumption on this connection.
382func (hs *serverHandshakeState) checkForResumption() bool {
383 c := hs.c
384
David Benjaminc565ebb2015-04-03 04:06:36 -0400385 if c.config.Bugs.NeverResumeOnRenego && c.cipherSuite != nil {
David Benjamincdea40c2015-03-19 14:09:43 -0400386 return false
387 }
388
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500389 if len(hs.clientHello.sessionTicket) > 0 {
390 if c.config.SessionTicketsDisabled {
391 return false
392 }
David Benjaminb0c8db72014-09-24 15:19:56 -0400393
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500394 var ok bool
395 if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
396 return false
397 }
398 } else {
399 if c.config.ServerSessionCache == nil {
400 return false
401 }
402
403 var ok bool
404 sessionId := string(hs.clientHello.sessionId)
405 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
406 return false
407 }
Adam Langley95c29f32014-06-20 12:00:00 -0700408 }
409
David Benjamine18d8212014-11-10 02:37:15 -0500410 // Never resume a session for a different SSL version.
411 if !c.config.Bugs.AllowSessionVersionMismatch && c.vers != hs.sessionState.vers {
412 return false
Adam Langley95c29f32014-06-20 12:00:00 -0700413 }
414
415 cipherSuiteOk := false
416 // Check that the client is still offering the ciphersuite in the session.
417 for _, id := range hs.clientHello.cipherSuites {
418 if id == hs.sessionState.cipherSuite {
419 cipherSuiteOk = true
420 break
421 }
422 }
423 if !cipherSuiteOk {
424 return false
425 }
426
427 // Check that we also support the ciphersuite from the session.
428 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk)
429 if hs.suite == nil {
430 return false
431 }
432
433 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
434 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
435 if needClientCerts && !sessionHasClientCerts {
436 return false
437 }
438 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
439 return false
440 }
441
442 return true
443}
444
445func (hs *serverHandshakeState) doResumeHandshake() error {
446 c := hs.c
447
448 hs.hello.cipherSuite = hs.suite.id
David Benjaminece3de92015-03-16 18:02:20 -0400449 if c.config.Bugs.SendCipherSuite != 0 {
450 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
451 }
Adam Langley95c29f32014-06-20 12:00:00 -0700452 // We echo the client's session ID in the ServerHello to let it know
453 // that we're doing a resumption.
454 hs.hello.sessionId = hs.clientHello.sessionId
David Benjaminbed9aae2014-08-07 19:13:38 -0400455 hs.hello.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -0700456
457 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -0400458 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -0400459 hs.writeClientHash(hs.clientHello.marshal())
460 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700461
462 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
463
464 if len(hs.sessionState.certificates) > 0 {
465 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
466 return err
467 }
468 }
469
470 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -0700471 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700472
473 return nil
474}
475
476func (hs *serverHandshakeState) doFullHandshake() error {
477 config := hs.c.config
478 c := hs.c
479
David Benjamin48cae082014-10-27 01:06:24 -0400480 isPSK := hs.suite.flags&suitePSK != 0
481 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700482 hs.hello.ocspStapling = true
483 }
484
David Benjamin61f95272014-11-25 01:55:35 -0500485 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
486 hs.hello.sctList = hs.cert.SignedCertificateTimestampList
487 }
488
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500489 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
Adam Langley95c29f32014-06-20 12:00:00 -0700490 hs.hello.cipherSuite = hs.suite.id
David Benjamin6095de82014-12-27 01:50:38 -0500491 if config.Bugs.SendCipherSuite != 0 {
492 hs.hello.cipherSuite = config.Bugs.SendCipherSuite
493 }
Adam Langley75712922014-10-10 16:23:43 -0700494 c.extendedMasterSecret = hs.hello.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700495
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500496 // Generate a session ID if we're to save the session.
497 if !hs.hello.ticketSupported && config.ServerSessionCache != nil {
498 hs.hello.sessionId = make([]byte, 32)
499 if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
500 c.sendAlert(alertInternalError)
501 return errors.New("tls: short read from Rand: " + err.Error())
502 }
503 }
504
Adam Langley95c29f32014-06-20 12:00:00 -0700505 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400506 hs.writeClientHash(hs.clientHello.marshal())
507 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700508
509 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
510
David Benjamin48cae082014-10-27 01:06:24 -0400511 if !isPSK {
512 certMsg := new(certificateMsg)
513 certMsg.certificates = hs.cert.Certificate
514 if !config.Bugs.UnauthenticatedECDH {
David Benjaminbcb2d912015-02-24 23:45:43 -0500515 certMsgBytes := certMsg.marshal()
516 if config.Bugs.WrongCertificateMessageType {
517 certMsgBytes[0] += 42
518 }
519 hs.writeServerHash(certMsgBytes)
520 c.writeRecord(recordTypeHandshake, certMsgBytes)
David Benjamin48cae082014-10-27 01:06:24 -0400521 }
David Benjamin1c375dd2014-07-12 00:48:23 -0400522 }
Adam Langley95c29f32014-06-20 12:00:00 -0700523
David Benjamindcd979f2015-04-20 18:26:52 -0400524 if hs.hello.ocspStapling && !c.config.Bugs.SkipCertificateStatus {
Adam Langley95c29f32014-06-20 12:00:00 -0700525 certStatus := new(certificateStatusMsg)
526 certStatus.statusType = statusTypeOCSP
527 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -0400528 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700529 c.writeRecord(recordTypeHandshake, certStatus.marshal())
530 }
531
532 keyAgreement := hs.suite.ka(c.vers)
533 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
534 if err != nil {
535 c.sendAlert(alertHandshakeFailure)
536 return err
537 }
David Benjamin9c651c92014-07-12 13:27:45 -0400538 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -0400539 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700540 c.writeRecord(recordTypeHandshake, skx.marshal())
541 }
542
543 if config.ClientAuth >= RequestClientCert {
544 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -0400545 certReq := &certificateRequestMsg{
546 certificateTypes: config.ClientCertificateTypes,
547 }
548 if certReq.certificateTypes == nil {
549 certReq.certificateTypes = []byte{
550 byte(CertTypeRSASign),
551 byte(CertTypeECDSASign),
552 }
Adam Langley95c29f32014-06-20 12:00:00 -0700553 }
554 if c.vers >= VersionTLS12 {
555 certReq.hasSignatureAndHash = true
David Benjamin000800a2014-11-14 01:43:59 -0500556 if !config.Bugs.NoSignatureAndHashes {
557 certReq.signatureAndHashes = config.signatureAndHashesForServer()
558 }
Adam Langley95c29f32014-06-20 12:00:00 -0700559 }
560
561 // An empty list of certificateAuthorities signals to
562 // the client that it may send any certificate in response
563 // to our request. When we know the CAs we trust, then
564 // we can send them down, so that the client can choose
565 // an appropriate certificate to give to us.
566 if config.ClientCAs != nil {
567 certReq.certificateAuthorities = config.ClientCAs.Subjects()
568 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400569 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700570 c.writeRecord(recordTypeHandshake, certReq.marshal())
571 }
572
573 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400574 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700575 c.writeRecord(recordTypeHandshake, helloDone.marshal())
David Benjamina4e6d482015-03-02 19:10:53 -0500576 c.dtlsFlushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700577
578 var pub crypto.PublicKey // public key for client auth, if any
579
David Benjamin83f90402015-01-27 01:09:43 -0500580 if err := c.simulatePacketLoss(nil); err != nil {
581 return err
582 }
Adam Langley95c29f32014-06-20 12:00:00 -0700583 msg, err := c.readHandshake()
584 if err != nil {
585 return err
586 }
587
588 var ok bool
589 // If we requested a client certificate, then the client must send a
590 // certificate message, even if it's empty.
591 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -0400592 var certMsg *certificateMsg
Adam Langley95c29f32014-06-20 12:00:00 -0700593 if certMsg, ok = msg.(*certificateMsg); !ok {
594 c.sendAlert(alertUnexpectedMessage)
595 return unexpectedMessageError(certMsg, msg)
596 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400597 hs.writeClientHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700598
599 if len(certMsg.certificates) == 0 {
600 // The client didn't actually send a certificate
601 switch config.ClientAuth {
602 case RequireAnyClientCert, RequireAndVerifyClientCert:
603 c.sendAlert(alertBadCertificate)
604 return errors.New("tls: client didn't provide a certificate")
605 }
606 }
607
608 pub, err = hs.processCertsFromClient(certMsg.certificates)
609 if err != nil {
610 return err
611 }
612
613 msg, err = c.readHandshake()
614 if err != nil {
615 return err
616 }
617 }
618
619 // Get client key exchange
620 ckx, ok := msg.(*clientKeyExchangeMsg)
621 if !ok {
622 c.sendAlert(alertUnexpectedMessage)
623 return unexpectedMessageError(ckx, msg)
624 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400625 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700626
David Benjamine098ec22014-08-27 23:13:20 -0400627 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
628 if err != nil {
629 c.sendAlert(alertHandshakeFailure)
630 return err
631 }
Adam Langley75712922014-10-10 16:23:43 -0700632 if c.extendedMasterSecret {
633 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
634 } else {
635 if c.config.Bugs.RequireExtendedMasterSecret {
636 return errors.New("tls: extended master secret required but not supported by peer")
637 }
638 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
639 }
David Benjamine098ec22014-08-27 23:13:20 -0400640
Adam Langley95c29f32014-06-20 12:00:00 -0700641 // If we received a client cert in response to our certificate request message,
642 // the client will send us a certificateVerifyMsg immediately after the
643 // clientKeyExchangeMsg. This message is a digest of all preceding
644 // handshake-layer messages that is signed using the private key corresponding
645 // to the client's certificate. This allows us to verify that the client is in
646 // possession of the private key of the certificate.
647 if len(c.peerCertificates) > 0 {
648 msg, err = c.readHandshake()
649 if err != nil {
650 return err
651 }
652 certVerify, ok := msg.(*certificateVerifyMsg)
653 if !ok {
654 c.sendAlert(alertUnexpectedMessage)
655 return unexpectedMessageError(certVerify, msg)
656 }
657
David Benjaminde620d92014-07-18 15:03:41 -0400658 // Determine the signature type.
659 var signatureAndHash signatureAndHash
660 if certVerify.hasSignatureAndHash {
661 signatureAndHash = certVerify.signatureAndHash
David Benjamin000800a2014-11-14 01:43:59 -0500662 if !isSupportedSignatureAndHash(signatureAndHash, config.signatureAndHashesForServer()) {
663 return errors.New("tls: unsupported hash function for client certificate")
664 }
David Benjaminde620d92014-07-18 15:03:41 -0400665 } else {
666 // Before TLS 1.2 the signature algorithm was implicit
667 // from the key type, and only one hash per signature
668 // algorithm was possible. Leave the hash as zero.
669 switch pub.(type) {
670 case *ecdsa.PublicKey:
671 signatureAndHash.signature = signatureECDSA
672 case *rsa.PublicKey:
673 signatureAndHash.signature = signatureRSA
674 }
675 }
676
Adam Langley95c29f32014-06-20 12:00:00 -0700677 switch key := pub.(type) {
678 case *ecdsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400679 if signatureAndHash.signature != signatureECDSA {
680 err = errors.New("tls: bad signature type for client's ECDSA certificate")
681 break
682 }
Adam Langley95c29f32014-06-20 12:00:00 -0700683 ecdsaSig := new(ecdsaSignature)
684 if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {
685 break
686 }
687 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
688 err = errors.New("ECDSA signature contained zero or negative values")
689 break
690 }
David Benjaminde620d92014-07-18 15:03:41 -0400691 var digest []byte
David Benjamine098ec22014-08-27 23:13:20 -0400692 digest, _, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400693 if err != nil {
694 break
695 }
Adam Langley95c29f32014-06-20 12:00:00 -0700696 if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {
697 err = errors.New("ECDSA verification failure")
698 break
699 }
700 case *rsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400701 if signatureAndHash.signature != signatureRSA {
702 err = errors.New("tls: bad signature type for client's RSA certificate")
703 break
704 }
705 var digest []byte
706 var hashFunc crypto.Hash
David Benjamine098ec22014-08-27 23:13:20 -0400707 digest, hashFunc, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400708 if err != nil {
709 break
710 }
Adam Langley95c29f32014-06-20 12:00:00 -0700711 err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)
712 }
713 if err != nil {
714 c.sendAlert(alertBadCertificate)
715 return errors.New("could not validate signature of connection nonces: " + err.Error())
716 }
717
David Benjamin83c0bc92014-08-04 01:23:53 -0400718 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700719 }
720
David Benjamine098ec22014-08-27 23:13:20 -0400721 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -0700722
723 return nil
724}
725
726func (hs *serverHandshakeState) establishKeys() error {
727 c := hs.c
728
729 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
730 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
731
732 var clientCipher, serverCipher interface{}
733 var clientHash, serverHash macFunction
734
735 if hs.suite.aead == nil {
736 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
737 clientHash = hs.suite.mac(c.vers, clientMAC)
738 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
739 serverHash = hs.suite.mac(c.vers, serverMAC)
740 } else {
741 clientCipher = hs.suite.aead(clientKey, clientIV)
742 serverCipher = hs.suite.aead(serverKey, serverIV)
743 }
744
745 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
746 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
747
748 return nil
749}
750
David Benjamind30a9902014-08-24 01:44:23 -0400751func (hs *serverHandshakeState) readFinished(isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700752 c := hs.c
753
754 c.readRecord(recordTypeChangeCipherSpec)
755 if err := c.in.error(); err != nil {
756 return err
757 }
758
759 if hs.hello.nextProtoNeg {
760 msg, err := c.readHandshake()
761 if err != nil {
762 return err
763 }
764 nextProto, ok := msg.(*nextProtoMsg)
765 if !ok {
766 c.sendAlert(alertUnexpectedMessage)
767 return unexpectedMessageError(nextProto, msg)
768 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400769 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700770 c.clientProtocol = nextProto.proto
771 }
772
David Benjamind30a9902014-08-24 01:44:23 -0400773 if hs.hello.channelIDRequested {
774 msg, err := c.readHandshake()
775 if err != nil {
776 return err
777 }
778 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
779 if !ok {
780 c.sendAlert(alertUnexpectedMessage)
781 return unexpectedMessageError(encryptedExtensions, msg)
782 }
783 x := new(big.Int).SetBytes(encryptedExtensions.channelID[0:32])
784 y := new(big.Int).SetBytes(encryptedExtensions.channelID[32:64])
785 r := new(big.Int).SetBytes(encryptedExtensions.channelID[64:96])
786 s := new(big.Int).SetBytes(encryptedExtensions.channelID[96:128])
787 if !elliptic.P256().IsOnCurve(x, y) {
788 return errors.New("tls: invalid channel ID public key")
789 }
790 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
791 var resumeHash []byte
792 if isResume {
793 resumeHash = hs.sessionState.handshakeHash
794 }
795 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
796 return errors.New("tls: invalid channel ID signature")
797 }
798 c.channelID = channelID
799
800 hs.writeClientHash(encryptedExtensions.marshal())
801 }
802
Adam Langley95c29f32014-06-20 12:00:00 -0700803 msg, err := c.readHandshake()
804 if err != nil {
805 return err
806 }
807 clientFinished, ok := msg.(*finishedMsg)
808 if !ok {
809 c.sendAlert(alertUnexpectedMessage)
810 return unexpectedMessageError(clientFinished, msg)
811 }
812
813 verify := hs.finishedHash.clientSum(hs.masterSecret)
814 if len(verify) != len(clientFinished.verifyData) ||
815 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
816 c.sendAlert(alertHandshakeFailure)
817 return errors.New("tls: client's Finished message is incorrect")
818 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700819 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langley95c29f32014-06-20 12:00:00 -0700820
David Benjamin83c0bc92014-08-04 01:23:53 -0400821 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700822 return nil
823}
824
825func (hs *serverHandshakeState) sendSessionTicket() error {
Adam Langley95c29f32014-06-20 12:00:00 -0700826 c := hs.c
Adam Langley95c29f32014-06-20 12:00:00 -0700827 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -0400828 vers: c.vers,
829 cipherSuite: hs.suite.id,
830 masterSecret: hs.masterSecret,
831 certificates: hs.certsFromClient,
832 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -0700833 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500834
835 if !hs.hello.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
836 if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
837 c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
838 }
839 return nil
840 }
841
842 m := new(newSessionTicketMsg)
843
844 var err error
Adam Langley95c29f32014-06-20 12:00:00 -0700845 m.ticket, err = c.encryptTicket(&state)
846 if err != nil {
847 return err
848 }
Adam Langley95c29f32014-06-20 12:00:00 -0700849
David Benjamin83c0bc92014-08-04 01:23:53 -0400850 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700851 c.writeRecord(recordTypeHandshake, m.marshal())
852
853 return nil
854}
855
856func (hs *serverHandshakeState) sendFinished() error {
857 c := hs.c
858
David Benjamin86271ee2014-07-21 16:14:03 -0400859 finished := new(finishedMsg)
860 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
David Benjamin513f0ea2015-04-02 19:33:31 -0400861 if c.config.Bugs.BadFinished {
862 finished.verifyData[0]++
863 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700864 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -0500865 hs.finishedBytes = finished.marshal()
866 hs.writeServerHash(hs.finishedBytes)
867 postCCSBytes := hs.finishedBytes
David Benjamin86271ee2014-07-21 16:14:03 -0400868
869 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
870 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
871 postCCSBytes = postCCSBytes[5:]
872 }
David Benjamina4e6d482015-03-02 19:10:53 -0500873 c.dtlsFlushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -0400874
David Benjamina0e52232014-07-19 17:39:58 -0400875 if !c.config.Bugs.SkipChangeCipherSpec {
876 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
877 }
Adam Langley95c29f32014-06-20 12:00:00 -0700878
David Benjamin4189bd92015-01-25 23:52:39 -0500879 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
880 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
881 }
David Benjamindc3da932015-03-12 15:09:02 -0400882 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
883 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
884 return errors.New("tls: simulating post-CCS alert")
885 }
David Benjamin4189bd92015-01-25 23:52:39 -0500886
David Benjaminb80168e2015-02-08 18:30:14 -0500887 if !c.config.Bugs.SkipFinished {
888 c.writeRecord(recordTypeHandshake, postCCSBytes)
David Benjamina4e6d482015-03-02 19:10:53 -0500889 c.dtlsFlushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -0500890 }
Adam Langley95c29f32014-06-20 12:00:00 -0700891
David Benjaminc565ebb2015-04-03 04:06:36 -0400892 c.cipherSuite = hs.suite
Adam Langley95c29f32014-06-20 12:00:00 -0700893
894 return nil
895}
896
897// processCertsFromClient takes a chain of client certificates either from a
898// Certificates message or from a sessionState and verifies them. It returns
899// the public key of the leaf certificate.
900func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
901 c := hs.c
902
903 hs.certsFromClient = certificates
904 certs := make([]*x509.Certificate, len(certificates))
905 var err error
906 for i, asn1Data := range certificates {
907 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
908 c.sendAlert(alertBadCertificate)
909 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
910 }
911 }
912
913 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
914 opts := x509.VerifyOptions{
915 Roots: c.config.ClientCAs,
916 CurrentTime: c.config.time(),
917 Intermediates: x509.NewCertPool(),
918 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
919 }
920
921 for _, cert := range certs[1:] {
922 opts.Intermediates.AddCert(cert)
923 }
924
925 chains, err := certs[0].Verify(opts)
926 if err != nil {
927 c.sendAlert(alertBadCertificate)
928 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
929 }
930
931 ok := false
932 for _, ku := range certs[0].ExtKeyUsage {
933 if ku == x509.ExtKeyUsageClientAuth {
934 ok = true
935 break
936 }
937 }
938 if !ok {
939 c.sendAlert(alertHandshakeFailure)
940 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
941 }
942
943 c.verifiedChains = chains
944 }
945
946 if len(certs) > 0 {
947 var pub crypto.PublicKey
948 switch key := certs[0].PublicKey.(type) {
949 case *ecdsa.PublicKey, *rsa.PublicKey:
950 pub = key
951 default:
952 c.sendAlert(alertUnsupportedCertificate)
953 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
954 }
955 c.peerCertificates = certs
956 return pub, nil
957 }
958
959 return nil, nil
960}
961
David Benjamin83c0bc92014-08-04 01:23:53 -0400962func (hs *serverHandshakeState) writeServerHash(msg []byte) {
963 // writeServerHash is called before writeRecord.
964 hs.writeHash(msg, hs.c.sendHandshakeSeq)
965}
966
967func (hs *serverHandshakeState) writeClientHash(msg []byte) {
968 // writeClientHash is called after readHandshake.
969 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
970}
971
972func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
973 if hs.c.isDTLS {
974 // This is somewhat hacky. DTLS hashes a slightly different format.
975 // First, the TLS header.
976 hs.finishedHash.Write(msg[:4])
977 // Then the sequence number and reassembled fragment offset (always 0).
978 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
979 // Then the reassembled fragment (always equal to the message length).
980 hs.finishedHash.Write(msg[1:4])
981 // And then the message body.
982 hs.finishedHash.Write(msg[4:])
983 } else {
984 hs.finishedHash.Write(msg)
985 }
986}
987
Adam Langley95c29f32014-06-20 12:00:00 -0700988// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
989// is acceptable to use.
990func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
991 for _, supported := range supportedCipherSuites {
992 if id == supported {
993 var candidate *cipherSuite
994
995 for _, s := range cipherSuites {
996 if s.id == id {
997 candidate = s
998 break
999 }
1000 }
1001 if candidate == nil {
1002 continue
1003 }
1004 // Don't select a ciphersuite which we can't
1005 // support for this client.
1006 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
1007 continue
1008 }
1009 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
1010 continue
1011 }
David Benjamin39ebf532014-08-31 02:23:49 -04001012 if !c.config.Bugs.SkipCipherVersionCheck && version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
Adam Langley95c29f32014-06-20 12:00:00 -07001013 continue
1014 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001015 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
1016 continue
1017 }
Adam Langley95c29f32014-06-20 12:00:00 -07001018 return candidate
1019 }
1020 }
1021
1022 return nil
1023}