blob: 46e0fb0e47f6317077fb5fec116236b6db1807c4 [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()
218Curves:
219 for _, curve := range hs.clientHello.supportedCurves {
220 for _, supported := range preferredCurves {
221 if supported == curve {
222 supportedCurve = true
223 break Curves
224 }
225 }
226 }
227
228 supportedPointFormat := false
229 for _, pointFormat := range hs.clientHello.supportedPoints {
230 if pointFormat == pointFormatUncompressed {
231 supportedPointFormat = true
232 break
233 }
234 }
235 hs.ellipticOk = supportedCurve && supportedPointFormat
236
237 foundCompression := false
238 // We only support null compression, so check that the client offered it.
239 for _, compression := range hs.clientHello.compressionMethods {
240 if compression == compressionNone {
241 foundCompression = true
242 break
243 }
244 }
245
246 if !foundCompression {
247 c.sendAlert(alertHandshakeFailure)
248 return false, errors.New("tls: client does not support uncompressed connections")
249 }
250
251 hs.hello.vers = c.vers
252 hs.hello.random = make([]byte, 32)
253 _, err = io.ReadFull(config.rand(), hs.hello.random)
254 if err != nil {
255 c.sendAlert(alertInternalError)
256 return false, err
257 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700258
Adam Langleycf2d4f42014-10-28 19:06:14 -0700259 if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) {
Adam Langley2ae77d22014-10-28 17:29:33 -0700260 c.sendAlert(alertHandshakeFailure)
Adam Langleycf2d4f42014-10-28 19:06:14 -0700261 return false, errors.New("tls: renegotiation mismatch")
Adam Langley2ae77d22014-10-28 17:29:33 -0700262 }
Adam Langleycf2d4f42014-10-28 19:06:14 -0700263
264 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
265 hs.hello.secureRenegotiation = append(hs.hello.secureRenegotiation, c.clientVerify...)
266 hs.hello.secureRenegotiation = append(hs.hello.secureRenegotiation, c.serverVerify...)
267 if c.config.Bugs.BadRenegotiationInfo {
268 hs.hello.secureRenegotiation[0] ^= 0x80
269 }
270 } else {
271 hs.hello.secureRenegotiation = hs.clientHello.secureRenegotiation
272 }
273
Adam Langley95c29f32014-06-20 12:00:00 -0700274 hs.hello.compressionMethod = compressionNone
David Benjamin35a7a442014-07-05 00:23:20 -0400275 hs.hello.duplicateExtension = c.config.Bugs.DuplicateExtension
Adam Langley95c29f32014-06-20 12:00:00 -0700276 if len(hs.clientHello.serverName) > 0 {
277 c.serverName = hs.clientHello.serverName
278 }
David Benjaminfa055a22014-09-15 16:51:51 -0400279
280 if len(hs.clientHello.alpnProtocols) > 0 {
281 if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
282 hs.hello.alpnProtocol = selectedProto
283 c.clientProtocol = selectedProto
David Benjaminfc7b0862014-09-06 13:21:53 -0400284 c.usedALPN = true
David Benjaminfa055a22014-09-15 16:51:51 -0400285 }
286 } else {
287 // Although sending an empty NPN extension is reasonable, Firefox has
288 // had a bug around this. Best to send nothing at all if
289 // config.NextProtos is empty. See
290 // https://code.google.com/p/go/issues/detail?id=5445.
291 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
292 hs.hello.nextProtoNeg = true
293 hs.hello.nextProtos = config.NextProtos
294 }
Adam Langley95c29f32014-06-20 12:00:00 -0700295 }
Adam Langley75712922014-10-10 16:23:43 -0700296 hs.hello.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !c.config.Bugs.NoExtendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700297
298 if len(config.Certificates) == 0 {
299 c.sendAlert(alertInternalError)
300 return false, errors.New("tls: no certificates configured")
301 }
302 hs.cert = &config.Certificates[0]
303 if len(hs.clientHello.serverName) > 0 {
304 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
305 }
David Benjamine78bfde2014-09-06 12:45:15 -0400306 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
307 return false, errors.New("tls: unexpected server name")
308 }
Adam Langley95c29f32014-06-20 12:00:00 -0700309
David Benjamind30a9902014-08-24 01:44:23 -0400310 if hs.clientHello.channelIDSupported && config.RequestChannelID {
311 hs.hello.channelIDRequested = true
312 }
313
David Benjaminca6c8262014-11-15 19:06:08 -0500314 if hs.clientHello.srtpProtectionProfiles != nil {
315 SRTPLoop:
316 for _, p1 := range c.config.SRTPProtectionProfiles {
317 for _, p2 := range hs.clientHello.srtpProtectionProfiles {
318 if p1 == p2 {
319 hs.hello.srtpProtectionProfile = p1
320 c.srtpProtectionProfile = p1
321 break SRTPLoop
322 }
323 }
324 }
325 }
326
327 if c.config.Bugs.SendSRTPProtectionProfile != 0 {
328 hs.hello.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
329 }
330
Adam Langley95c29f32014-06-20 12:00:00 -0700331 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
332
333 if hs.checkForResumption() {
334 return true, nil
335 }
336
Adam Langleyac61fa32014-06-23 12:03:11 -0700337 var scsvFound bool
338
339 for _, cipherSuite := range hs.clientHello.cipherSuites {
340 if cipherSuite == fallbackSCSV {
341 scsvFound = true
342 break
343 }
344 }
345
346 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
347 return false, errors.New("tls: no fallback SCSV found when expected")
348 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
349 return false, errors.New("tls: fallback SCSV found when not expected")
350 }
351
David Benjamin67d1fb52015-03-16 15:16:23 -0400352 if config.Bugs.IgnorePeerCipherPreferences {
353 hs.clientHello.cipherSuites = c.config.cipherSuites()
354 }
Adam Langley95c29f32014-06-20 12:00:00 -0700355 var preferenceList, supportedList []uint16
356 if c.config.PreferServerCipherSuites {
357 preferenceList = c.config.cipherSuites()
358 supportedList = hs.clientHello.cipherSuites
359 } else {
360 preferenceList = hs.clientHello.cipherSuites
361 supportedList = c.config.cipherSuites()
362 }
363
364 for _, id := range preferenceList {
365 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
366 break
367 }
368 }
369
370 if hs.suite == nil {
371 c.sendAlert(alertHandshakeFailure)
372 return false, errors.New("tls: no cipher suite supported by both client and server")
373 }
374
375 return false, nil
376}
377
378// checkForResumption returns true if we should perform resumption on this connection.
379func (hs *serverHandshakeState) checkForResumption() bool {
380 c := hs.c
381
David Benjaminc565ebb2015-04-03 04:06:36 -0400382 if c.config.Bugs.NeverResumeOnRenego && c.cipherSuite != nil {
David Benjamincdea40c2015-03-19 14:09:43 -0400383 return false
384 }
385
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500386 if len(hs.clientHello.sessionTicket) > 0 {
387 if c.config.SessionTicketsDisabled {
388 return false
389 }
David Benjaminb0c8db72014-09-24 15:19:56 -0400390
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500391 var ok bool
392 if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
393 return false
394 }
395 } else {
396 if c.config.ServerSessionCache == nil {
397 return false
398 }
399
400 var ok bool
401 sessionId := string(hs.clientHello.sessionId)
402 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
403 return false
404 }
Adam Langley95c29f32014-06-20 12:00:00 -0700405 }
406
David Benjamine18d8212014-11-10 02:37:15 -0500407 // Never resume a session for a different SSL version.
408 if !c.config.Bugs.AllowSessionVersionMismatch && c.vers != hs.sessionState.vers {
409 return false
Adam Langley95c29f32014-06-20 12:00:00 -0700410 }
411
412 cipherSuiteOk := false
413 // Check that the client is still offering the ciphersuite in the session.
414 for _, id := range hs.clientHello.cipherSuites {
415 if id == hs.sessionState.cipherSuite {
416 cipherSuiteOk = true
417 break
418 }
419 }
420 if !cipherSuiteOk {
421 return false
422 }
423
424 // Check that we also support the ciphersuite from the session.
425 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk)
426 if hs.suite == nil {
427 return false
428 }
429
430 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
431 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
432 if needClientCerts && !sessionHasClientCerts {
433 return false
434 }
435 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
436 return false
437 }
438
439 return true
440}
441
442func (hs *serverHandshakeState) doResumeHandshake() error {
443 c := hs.c
444
445 hs.hello.cipherSuite = hs.suite.id
David Benjaminece3de92015-03-16 18:02:20 -0400446 if c.config.Bugs.SendCipherSuite != 0 {
447 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
448 }
Adam Langley95c29f32014-06-20 12:00:00 -0700449 // We echo the client's session ID in the ServerHello to let it know
450 // that we're doing a resumption.
451 hs.hello.sessionId = hs.clientHello.sessionId
David Benjaminbed9aae2014-08-07 19:13:38 -0400452 hs.hello.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -0700453
454 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -0400455 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -0400456 hs.writeClientHash(hs.clientHello.marshal())
457 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700458
459 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
460
461 if len(hs.sessionState.certificates) > 0 {
462 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
463 return err
464 }
465 }
466
467 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -0700468 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700469
470 return nil
471}
472
473func (hs *serverHandshakeState) doFullHandshake() error {
474 config := hs.c.config
475 c := hs.c
476
David Benjamin48cae082014-10-27 01:06:24 -0400477 isPSK := hs.suite.flags&suitePSK != 0
478 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700479 hs.hello.ocspStapling = true
480 }
481
David Benjamin61f95272014-11-25 01:55:35 -0500482 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
483 hs.hello.sctList = hs.cert.SignedCertificateTimestampList
484 }
485
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500486 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
Adam Langley95c29f32014-06-20 12:00:00 -0700487 hs.hello.cipherSuite = hs.suite.id
David Benjamin6095de82014-12-27 01:50:38 -0500488 if config.Bugs.SendCipherSuite != 0 {
489 hs.hello.cipherSuite = config.Bugs.SendCipherSuite
490 }
Adam Langley75712922014-10-10 16:23:43 -0700491 c.extendedMasterSecret = hs.hello.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700492
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500493 // Generate a session ID if we're to save the session.
494 if !hs.hello.ticketSupported && config.ServerSessionCache != nil {
495 hs.hello.sessionId = make([]byte, 32)
496 if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
497 c.sendAlert(alertInternalError)
498 return errors.New("tls: short read from Rand: " + err.Error())
499 }
500 }
501
Adam Langley95c29f32014-06-20 12:00:00 -0700502 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400503 hs.writeClientHash(hs.clientHello.marshal())
504 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700505
506 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
507
David Benjamin48cae082014-10-27 01:06:24 -0400508 if !isPSK {
509 certMsg := new(certificateMsg)
510 certMsg.certificates = hs.cert.Certificate
511 if !config.Bugs.UnauthenticatedECDH {
David Benjaminbcb2d912015-02-24 23:45:43 -0500512 certMsgBytes := certMsg.marshal()
513 if config.Bugs.WrongCertificateMessageType {
514 certMsgBytes[0] += 42
515 }
516 hs.writeServerHash(certMsgBytes)
517 c.writeRecord(recordTypeHandshake, certMsgBytes)
David Benjamin48cae082014-10-27 01:06:24 -0400518 }
David Benjamin1c375dd2014-07-12 00:48:23 -0400519 }
Adam Langley95c29f32014-06-20 12:00:00 -0700520
521 if hs.hello.ocspStapling {
522 certStatus := new(certificateStatusMsg)
523 certStatus.statusType = statusTypeOCSP
524 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -0400525 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700526 c.writeRecord(recordTypeHandshake, certStatus.marshal())
527 }
528
529 keyAgreement := hs.suite.ka(c.vers)
530 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
531 if err != nil {
532 c.sendAlert(alertHandshakeFailure)
533 return err
534 }
David Benjamin9c651c92014-07-12 13:27:45 -0400535 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -0400536 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700537 c.writeRecord(recordTypeHandshake, skx.marshal())
538 }
539
540 if config.ClientAuth >= RequestClientCert {
541 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -0400542 certReq := &certificateRequestMsg{
543 certificateTypes: config.ClientCertificateTypes,
544 }
545 if certReq.certificateTypes == nil {
546 certReq.certificateTypes = []byte{
547 byte(CertTypeRSASign),
548 byte(CertTypeECDSASign),
549 }
Adam Langley95c29f32014-06-20 12:00:00 -0700550 }
551 if c.vers >= VersionTLS12 {
552 certReq.hasSignatureAndHash = true
David Benjamin000800a2014-11-14 01:43:59 -0500553 if !config.Bugs.NoSignatureAndHashes {
554 certReq.signatureAndHashes = config.signatureAndHashesForServer()
555 }
Adam Langley95c29f32014-06-20 12:00:00 -0700556 }
557
558 // An empty list of certificateAuthorities signals to
559 // the client that it may send any certificate in response
560 // to our request. When we know the CAs we trust, then
561 // we can send them down, so that the client can choose
562 // an appropriate certificate to give to us.
563 if config.ClientCAs != nil {
564 certReq.certificateAuthorities = config.ClientCAs.Subjects()
565 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400566 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700567 c.writeRecord(recordTypeHandshake, certReq.marshal())
568 }
569
570 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400571 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700572 c.writeRecord(recordTypeHandshake, helloDone.marshal())
David Benjamina4e6d482015-03-02 19:10:53 -0500573 c.dtlsFlushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700574
575 var pub crypto.PublicKey // public key for client auth, if any
576
David Benjamin83f90402015-01-27 01:09:43 -0500577 if err := c.simulatePacketLoss(nil); err != nil {
578 return err
579 }
Adam Langley95c29f32014-06-20 12:00:00 -0700580 msg, err := c.readHandshake()
581 if err != nil {
582 return err
583 }
584
585 var ok bool
586 // If we requested a client certificate, then the client must send a
587 // certificate message, even if it's empty.
588 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -0400589 var certMsg *certificateMsg
Adam Langley95c29f32014-06-20 12:00:00 -0700590 if certMsg, ok = msg.(*certificateMsg); !ok {
591 c.sendAlert(alertUnexpectedMessage)
592 return unexpectedMessageError(certMsg, msg)
593 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400594 hs.writeClientHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700595
596 if len(certMsg.certificates) == 0 {
597 // The client didn't actually send a certificate
598 switch config.ClientAuth {
599 case RequireAnyClientCert, RequireAndVerifyClientCert:
600 c.sendAlert(alertBadCertificate)
601 return errors.New("tls: client didn't provide a certificate")
602 }
603 }
604
605 pub, err = hs.processCertsFromClient(certMsg.certificates)
606 if err != nil {
607 return err
608 }
609
610 msg, err = c.readHandshake()
611 if err != nil {
612 return err
613 }
614 }
615
616 // Get client key exchange
617 ckx, ok := msg.(*clientKeyExchangeMsg)
618 if !ok {
619 c.sendAlert(alertUnexpectedMessage)
620 return unexpectedMessageError(ckx, msg)
621 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400622 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700623
David Benjamine098ec22014-08-27 23:13:20 -0400624 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
625 if err != nil {
626 c.sendAlert(alertHandshakeFailure)
627 return err
628 }
Adam Langley75712922014-10-10 16:23:43 -0700629 if c.extendedMasterSecret {
630 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
631 } else {
632 if c.config.Bugs.RequireExtendedMasterSecret {
633 return errors.New("tls: extended master secret required but not supported by peer")
634 }
635 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
636 }
David Benjamine098ec22014-08-27 23:13:20 -0400637
Adam Langley95c29f32014-06-20 12:00:00 -0700638 // If we received a client cert in response to our certificate request message,
639 // the client will send us a certificateVerifyMsg immediately after the
640 // clientKeyExchangeMsg. This message is a digest of all preceding
641 // handshake-layer messages that is signed using the private key corresponding
642 // to the client's certificate. This allows us to verify that the client is in
643 // possession of the private key of the certificate.
644 if len(c.peerCertificates) > 0 {
645 msg, err = c.readHandshake()
646 if err != nil {
647 return err
648 }
649 certVerify, ok := msg.(*certificateVerifyMsg)
650 if !ok {
651 c.sendAlert(alertUnexpectedMessage)
652 return unexpectedMessageError(certVerify, msg)
653 }
654
David Benjaminde620d92014-07-18 15:03:41 -0400655 // Determine the signature type.
656 var signatureAndHash signatureAndHash
657 if certVerify.hasSignatureAndHash {
658 signatureAndHash = certVerify.signatureAndHash
David Benjamin000800a2014-11-14 01:43:59 -0500659 if !isSupportedSignatureAndHash(signatureAndHash, config.signatureAndHashesForServer()) {
660 return errors.New("tls: unsupported hash function for client certificate")
661 }
David Benjaminde620d92014-07-18 15:03:41 -0400662 } else {
663 // Before TLS 1.2 the signature algorithm was implicit
664 // from the key type, and only one hash per signature
665 // algorithm was possible. Leave the hash as zero.
666 switch pub.(type) {
667 case *ecdsa.PublicKey:
668 signatureAndHash.signature = signatureECDSA
669 case *rsa.PublicKey:
670 signatureAndHash.signature = signatureRSA
671 }
672 }
673
Adam Langley95c29f32014-06-20 12:00:00 -0700674 switch key := pub.(type) {
675 case *ecdsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400676 if signatureAndHash.signature != signatureECDSA {
677 err = errors.New("tls: bad signature type for client's ECDSA certificate")
678 break
679 }
Adam Langley95c29f32014-06-20 12:00:00 -0700680 ecdsaSig := new(ecdsaSignature)
681 if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {
682 break
683 }
684 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
685 err = errors.New("ECDSA signature contained zero or negative values")
686 break
687 }
David Benjaminde620d92014-07-18 15:03:41 -0400688 var digest []byte
David Benjamine098ec22014-08-27 23:13:20 -0400689 digest, _, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400690 if err != nil {
691 break
692 }
Adam Langley95c29f32014-06-20 12:00:00 -0700693 if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {
694 err = errors.New("ECDSA verification failure")
695 break
696 }
697 case *rsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400698 if signatureAndHash.signature != signatureRSA {
699 err = errors.New("tls: bad signature type for client's RSA certificate")
700 break
701 }
702 var digest []byte
703 var hashFunc crypto.Hash
David Benjamine098ec22014-08-27 23:13:20 -0400704 digest, hashFunc, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400705 if err != nil {
706 break
707 }
Adam Langley95c29f32014-06-20 12:00:00 -0700708 err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)
709 }
710 if err != nil {
711 c.sendAlert(alertBadCertificate)
712 return errors.New("could not validate signature of connection nonces: " + err.Error())
713 }
714
David Benjamin83c0bc92014-08-04 01:23:53 -0400715 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700716 }
717
David Benjamine098ec22014-08-27 23:13:20 -0400718 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -0700719
720 return nil
721}
722
723func (hs *serverHandshakeState) establishKeys() error {
724 c := hs.c
725
726 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
727 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
728
729 var clientCipher, serverCipher interface{}
730 var clientHash, serverHash macFunction
731
732 if hs.suite.aead == nil {
733 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
734 clientHash = hs.suite.mac(c.vers, clientMAC)
735 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
736 serverHash = hs.suite.mac(c.vers, serverMAC)
737 } else {
738 clientCipher = hs.suite.aead(clientKey, clientIV)
739 serverCipher = hs.suite.aead(serverKey, serverIV)
740 }
741
742 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
743 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
744
745 return nil
746}
747
David Benjamind30a9902014-08-24 01:44:23 -0400748func (hs *serverHandshakeState) readFinished(isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700749 c := hs.c
750
751 c.readRecord(recordTypeChangeCipherSpec)
752 if err := c.in.error(); err != nil {
753 return err
754 }
755
756 if hs.hello.nextProtoNeg {
757 msg, err := c.readHandshake()
758 if err != nil {
759 return err
760 }
761 nextProto, ok := msg.(*nextProtoMsg)
762 if !ok {
763 c.sendAlert(alertUnexpectedMessage)
764 return unexpectedMessageError(nextProto, msg)
765 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400766 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700767 c.clientProtocol = nextProto.proto
768 }
769
David Benjamind30a9902014-08-24 01:44:23 -0400770 if hs.hello.channelIDRequested {
771 msg, err := c.readHandshake()
772 if err != nil {
773 return err
774 }
775 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
776 if !ok {
777 c.sendAlert(alertUnexpectedMessage)
778 return unexpectedMessageError(encryptedExtensions, msg)
779 }
780 x := new(big.Int).SetBytes(encryptedExtensions.channelID[0:32])
781 y := new(big.Int).SetBytes(encryptedExtensions.channelID[32:64])
782 r := new(big.Int).SetBytes(encryptedExtensions.channelID[64:96])
783 s := new(big.Int).SetBytes(encryptedExtensions.channelID[96:128])
784 if !elliptic.P256().IsOnCurve(x, y) {
785 return errors.New("tls: invalid channel ID public key")
786 }
787 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
788 var resumeHash []byte
789 if isResume {
790 resumeHash = hs.sessionState.handshakeHash
791 }
792 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
793 return errors.New("tls: invalid channel ID signature")
794 }
795 c.channelID = channelID
796
797 hs.writeClientHash(encryptedExtensions.marshal())
798 }
799
Adam Langley95c29f32014-06-20 12:00:00 -0700800 msg, err := c.readHandshake()
801 if err != nil {
802 return err
803 }
804 clientFinished, ok := msg.(*finishedMsg)
805 if !ok {
806 c.sendAlert(alertUnexpectedMessage)
807 return unexpectedMessageError(clientFinished, msg)
808 }
809
810 verify := hs.finishedHash.clientSum(hs.masterSecret)
811 if len(verify) != len(clientFinished.verifyData) ||
812 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
813 c.sendAlert(alertHandshakeFailure)
814 return errors.New("tls: client's Finished message is incorrect")
815 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700816 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langley95c29f32014-06-20 12:00:00 -0700817
David Benjamin83c0bc92014-08-04 01:23:53 -0400818 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700819 return nil
820}
821
822func (hs *serverHandshakeState) sendSessionTicket() error {
Adam Langley95c29f32014-06-20 12:00:00 -0700823 c := hs.c
Adam Langley95c29f32014-06-20 12:00:00 -0700824 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -0400825 vers: c.vers,
826 cipherSuite: hs.suite.id,
827 masterSecret: hs.masterSecret,
828 certificates: hs.certsFromClient,
829 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -0700830 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500831
832 if !hs.hello.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
833 if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
834 c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
835 }
836 return nil
837 }
838
839 m := new(newSessionTicketMsg)
840
841 var err error
Adam Langley95c29f32014-06-20 12:00:00 -0700842 m.ticket, err = c.encryptTicket(&state)
843 if err != nil {
844 return err
845 }
Adam Langley95c29f32014-06-20 12:00:00 -0700846
David Benjamin83c0bc92014-08-04 01:23:53 -0400847 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700848 c.writeRecord(recordTypeHandshake, m.marshal())
849
850 return nil
851}
852
853func (hs *serverHandshakeState) sendFinished() error {
854 c := hs.c
855
David Benjamin86271ee2014-07-21 16:14:03 -0400856 finished := new(finishedMsg)
857 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
David Benjamin513f0ea2015-04-02 19:33:31 -0400858 if c.config.Bugs.BadFinished {
859 finished.verifyData[0]++
860 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700861 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -0500862 hs.finishedBytes = finished.marshal()
863 hs.writeServerHash(hs.finishedBytes)
864 postCCSBytes := hs.finishedBytes
David Benjamin86271ee2014-07-21 16:14:03 -0400865
866 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
867 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
868 postCCSBytes = postCCSBytes[5:]
869 }
David Benjamina4e6d482015-03-02 19:10:53 -0500870 c.dtlsFlushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -0400871
David Benjamina0e52232014-07-19 17:39:58 -0400872 if !c.config.Bugs.SkipChangeCipherSpec {
873 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
874 }
Adam Langley95c29f32014-06-20 12:00:00 -0700875
David Benjamin4189bd92015-01-25 23:52:39 -0500876 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
877 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
878 }
David Benjamindc3da932015-03-12 15:09:02 -0400879 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
880 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
881 return errors.New("tls: simulating post-CCS alert")
882 }
David Benjamin4189bd92015-01-25 23:52:39 -0500883
David Benjaminb80168e2015-02-08 18:30:14 -0500884 if !c.config.Bugs.SkipFinished {
885 c.writeRecord(recordTypeHandshake, postCCSBytes)
David Benjamina4e6d482015-03-02 19:10:53 -0500886 c.dtlsFlushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -0500887 }
Adam Langley95c29f32014-06-20 12:00:00 -0700888
David Benjaminc565ebb2015-04-03 04:06:36 -0400889 c.cipherSuite = hs.suite
Adam Langley95c29f32014-06-20 12:00:00 -0700890
891 return nil
892}
893
894// processCertsFromClient takes a chain of client certificates either from a
895// Certificates message or from a sessionState and verifies them. It returns
896// the public key of the leaf certificate.
897func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
898 c := hs.c
899
900 hs.certsFromClient = certificates
901 certs := make([]*x509.Certificate, len(certificates))
902 var err error
903 for i, asn1Data := range certificates {
904 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
905 c.sendAlert(alertBadCertificate)
906 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
907 }
908 }
909
910 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
911 opts := x509.VerifyOptions{
912 Roots: c.config.ClientCAs,
913 CurrentTime: c.config.time(),
914 Intermediates: x509.NewCertPool(),
915 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
916 }
917
918 for _, cert := range certs[1:] {
919 opts.Intermediates.AddCert(cert)
920 }
921
922 chains, err := certs[0].Verify(opts)
923 if err != nil {
924 c.sendAlert(alertBadCertificate)
925 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
926 }
927
928 ok := false
929 for _, ku := range certs[0].ExtKeyUsage {
930 if ku == x509.ExtKeyUsageClientAuth {
931 ok = true
932 break
933 }
934 }
935 if !ok {
936 c.sendAlert(alertHandshakeFailure)
937 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
938 }
939
940 c.verifiedChains = chains
941 }
942
943 if len(certs) > 0 {
944 var pub crypto.PublicKey
945 switch key := certs[0].PublicKey.(type) {
946 case *ecdsa.PublicKey, *rsa.PublicKey:
947 pub = key
948 default:
949 c.sendAlert(alertUnsupportedCertificate)
950 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
951 }
952 c.peerCertificates = certs
953 return pub, nil
954 }
955
956 return nil, nil
957}
958
David Benjamin83c0bc92014-08-04 01:23:53 -0400959func (hs *serverHandshakeState) writeServerHash(msg []byte) {
960 // writeServerHash is called before writeRecord.
961 hs.writeHash(msg, hs.c.sendHandshakeSeq)
962}
963
964func (hs *serverHandshakeState) writeClientHash(msg []byte) {
965 // writeClientHash is called after readHandshake.
966 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
967}
968
969func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
970 if hs.c.isDTLS {
971 // This is somewhat hacky. DTLS hashes a slightly different format.
972 // First, the TLS header.
973 hs.finishedHash.Write(msg[:4])
974 // Then the sequence number and reassembled fragment offset (always 0).
975 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
976 // Then the reassembled fragment (always equal to the message length).
977 hs.finishedHash.Write(msg[1:4])
978 // And then the message body.
979 hs.finishedHash.Write(msg[4:])
980 } else {
981 hs.finishedHash.Write(msg)
982 }
983}
984
Adam Langley95c29f32014-06-20 12:00:00 -0700985// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
986// is acceptable to use.
987func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
988 for _, supported := range supportedCipherSuites {
989 if id == supported {
990 var candidate *cipherSuite
991
992 for _, s := range cipherSuites {
993 if s.id == id {
994 candidate = s
995 break
996 }
997 }
998 if candidate == nil {
999 continue
1000 }
1001 // Don't select a ciphersuite which we can't
1002 // support for this client.
1003 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
1004 continue
1005 }
1006 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
1007 continue
1008 }
David Benjamin39ebf532014-08-31 02:23:49 -04001009 if !c.config.Bugs.SkipCipherVersionCheck && version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
Adam Langley95c29f32014-06-20 12:00:00 -07001010 continue
1011 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001012 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
1013 continue
1014 }
Adam Langley95c29f32014-06-20 12:00:00 -07001015 return candidate
1016 }
1017 }
1018
1019 return nil
1020}