blob: 220e30caae99f25a83447cc8a68c0fc592a9af53 [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 Langleyaf0e32c2015-06-03 09:57:23 -070072 if err := hs.sendFinished(c.firstFinished[:]); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -070073 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 }
Adam Langleyaf0e32c2015-06-03 09:57:23 -070084 if err := hs.readFinished(nil, 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 }
Adam Langleyaf0e32c2015-06-03 09:57:23 -070097 if err := hs.readFinished(c.firstFinished[:], 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 }
Adam Langleyaf0e32c2015-06-03 09:57:23 -0700111 if err := hs.sendFinished(nil); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700112 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
David Benjamincff0b902015-05-15 23:09:47 -0400277 if c.config.Bugs.NoRenegotiationInfo {
278 hs.hello.secureRenegotiation = nil
279 }
280
Adam Langley95c29f32014-06-20 12:00:00 -0700281 hs.hello.compressionMethod = compressionNone
David Benjamin35a7a442014-07-05 00:23:20 -0400282 hs.hello.duplicateExtension = c.config.Bugs.DuplicateExtension
Adam Langley95c29f32014-06-20 12:00:00 -0700283 if len(hs.clientHello.serverName) > 0 {
284 c.serverName = hs.clientHello.serverName
285 }
David Benjaminfa055a22014-09-15 16:51:51 -0400286
287 if len(hs.clientHello.alpnProtocols) > 0 {
288 if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
289 hs.hello.alpnProtocol = selectedProto
290 c.clientProtocol = selectedProto
David Benjaminfc7b0862014-09-06 13:21:53 -0400291 c.usedALPN = true
David Benjaminfa055a22014-09-15 16:51:51 -0400292 }
293 } else {
294 // Although sending an empty NPN extension is reasonable, Firefox has
295 // had a bug around this. Best to send nothing at all if
296 // config.NextProtos is empty. See
297 // https://code.google.com/p/go/issues/detail?id=5445.
298 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
299 hs.hello.nextProtoNeg = true
300 hs.hello.nextProtos = config.NextProtos
301 }
Adam Langley95c29f32014-06-20 12:00:00 -0700302 }
Adam Langley75712922014-10-10 16:23:43 -0700303 hs.hello.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !c.config.Bugs.NoExtendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700304
305 if len(config.Certificates) == 0 {
306 c.sendAlert(alertInternalError)
307 return false, errors.New("tls: no certificates configured")
308 }
309 hs.cert = &config.Certificates[0]
310 if len(hs.clientHello.serverName) > 0 {
311 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
312 }
David Benjamine78bfde2014-09-06 12:45:15 -0400313 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
314 return false, errors.New("tls: unexpected server name")
315 }
Adam Langley95c29f32014-06-20 12:00:00 -0700316
David Benjamind30a9902014-08-24 01:44:23 -0400317 if hs.clientHello.channelIDSupported && config.RequestChannelID {
318 hs.hello.channelIDRequested = true
319 }
320
David Benjaminca6c8262014-11-15 19:06:08 -0500321 if hs.clientHello.srtpProtectionProfiles != nil {
322 SRTPLoop:
323 for _, p1 := range c.config.SRTPProtectionProfiles {
324 for _, p2 := range hs.clientHello.srtpProtectionProfiles {
325 if p1 == p2 {
326 hs.hello.srtpProtectionProfile = p1
327 c.srtpProtectionProfile = p1
328 break SRTPLoop
329 }
330 }
331 }
332 }
333
334 if c.config.Bugs.SendSRTPProtectionProfile != 0 {
335 hs.hello.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
336 }
337
Adam Langley95c29f32014-06-20 12:00:00 -0700338 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
339
David Benjamin4b27d9f2015-05-12 22:42:52 -0400340 // For test purposes, check that the peer never offers a session when
341 // renegotiating.
342 if c.cipherSuite != nil && len(hs.clientHello.sessionId) > 0 && c.config.Bugs.FailIfResumeOnRenego {
343 return false, errors.New("tls: offered resumption on renegotiation")
344 }
345
Adam Langley95c29f32014-06-20 12:00:00 -0700346 if hs.checkForResumption() {
347 return true, nil
348 }
349
Adam Langleyac61fa32014-06-23 12:03:11 -0700350 var scsvFound bool
351
352 for _, cipherSuite := range hs.clientHello.cipherSuites {
353 if cipherSuite == fallbackSCSV {
354 scsvFound = true
355 break
356 }
357 }
358
359 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
360 return false, errors.New("tls: no fallback SCSV found when expected")
361 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
362 return false, errors.New("tls: fallback SCSV found when not expected")
363 }
364
David Benjamin67d1fb52015-03-16 15:16:23 -0400365 if config.Bugs.IgnorePeerCipherPreferences {
366 hs.clientHello.cipherSuites = c.config.cipherSuites()
367 }
Adam Langley95c29f32014-06-20 12:00:00 -0700368 var preferenceList, supportedList []uint16
369 if c.config.PreferServerCipherSuites {
370 preferenceList = c.config.cipherSuites()
371 supportedList = hs.clientHello.cipherSuites
372 } else {
373 preferenceList = hs.clientHello.cipherSuites
374 supportedList = c.config.cipherSuites()
375 }
376
377 for _, id := range preferenceList {
378 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
379 break
380 }
381 }
382
383 if hs.suite == nil {
384 c.sendAlert(alertHandshakeFailure)
385 return false, errors.New("tls: no cipher suite supported by both client and server")
386 }
387
388 return false, nil
389}
390
391// checkForResumption returns true if we should perform resumption on this connection.
392func (hs *serverHandshakeState) checkForResumption() bool {
393 c := hs.c
394
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500395 if len(hs.clientHello.sessionTicket) > 0 {
396 if c.config.SessionTicketsDisabled {
397 return false
398 }
David Benjaminb0c8db72014-09-24 15:19:56 -0400399
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500400 var ok bool
401 if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
402 return false
403 }
404 } else {
405 if c.config.ServerSessionCache == nil {
406 return false
407 }
408
409 var ok bool
410 sessionId := string(hs.clientHello.sessionId)
411 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
412 return false
413 }
Adam Langley95c29f32014-06-20 12:00:00 -0700414 }
415
David Benjamine18d8212014-11-10 02:37:15 -0500416 // Never resume a session for a different SSL version.
417 if !c.config.Bugs.AllowSessionVersionMismatch && c.vers != hs.sessionState.vers {
418 return false
Adam Langley95c29f32014-06-20 12:00:00 -0700419 }
420
421 cipherSuiteOk := false
422 // Check that the client is still offering the ciphersuite in the session.
423 for _, id := range hs.clientHello.cipherSuites {
424 if id == hs.sessionState.cipherSuite {
425 cipherSuiteOk = true
426 break
427 }
428 }
429 if !cipherSuiteOk {
430 return false
431 }
432
433 // Check that we also support the ciphersuite from the session.
434 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk)
435 if hs.suite == nil {
436 return false
437 }
438
439 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
440 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
441 if needClientCerts && !sessionHasClientCerts {
442 return false
443 }
444 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
445 return false
446 }
447
448 return true
449}
450
451func (hs *serverHandshakeState) doResumeHandshake() error {
452 c := hs.c
453
454 hs.hello.cipherSuite = hs.suite.id
David Benjaminece3de92015-03-16 18:02:20 -0400455 if c.config.Bugs.SendCipherSuite != 0 {
456 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
457 }
Adam Langley95c29f32014-06-20 12:00:00 -0700458 // We echo the client's session ID in the ServerHello to let it know
459 // that we're doing a resumption.
460 hs.hello.sessionId = hs.clientHello.sessionId
David Benjaminbed9aae2014-08-07 19:13:38 -0400461 hs.hello.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -0700462
463 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -0400464 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -0400465 hs.writeClientHash(hs.clientHello.marshal())
466 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700467
468 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
469
470 if len(hs.sessionState.certificates) > 0 {
471 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
472 return err
473 }
474 }
475
476 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -0700477 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700478
479 return nil
480}
481
482func (hs *serverHandshakeState) doFullHandshake() error {
483 config := hs.c.config
484 c := hs.c
485
David Benjamin48cae082014-10-27 01:06:24 -0400486 isPSK := hs.suite.flags&suitePSK != 0
487 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700488 hs.hello.ocspStapling = true
489 }
490
David Benjamin61f95272014-11-25 01:55:35 -0500491 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
492 hs.hello.sctList = hs.cert.SignedCertificateTimestampList
493 }
494
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500495 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
Adam Langley95c29f32014-06-20 12:00:00 -0700496 hs.hello.cipherSuite = hs.suite.id
David Benjamin6095de82014-12-27 01:50:38 -0500497 if config.Bugs.SendCipherSuite != 0 {
498 hs.hello.cipherSuite = config.Bugs.SendCipherSuite
499 }
Adam Langley75712922014-10-10 16:23:43 -0700500 c.extendedMasterSecret = hs.hello.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700501
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500502 // Generate a session ID if we're to save the session.
503 if !hs.hello.ticketSupported && config.ServerSessionCache != nil {
504 hs.hello.sessionId = make([]byte, 32)
505 if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
506 c.sendAlert(alertInternalError)
507 return errors.New("tls: short read from Rand: " + err.Error())
508 }
509 }
510
Adam Langley95c29f32014-06-20 12:00:00 -0700511 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400512 hs.writeClientHash(hs.clientHello.marshal())
513 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700514
515 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
516
David Benjamin48cae082014-10-27 01:06:24 -0400517 if !isPSK {
518 certMsg := new(certificateMsg)
David Benjamin8923c0b2015-06-07 11:42:34 -0400519 if !config.Bugs.EmptyCertificateList {
520 certMsg.certificates = hs.cert.Certificate
521 }
David Benjamin48cae082014-10-27 01:06:24 -0400522 if !config.Bugs.UnauthenticatedECDH {
David Benjaminbcb2d912015-02-24 23:45:43 -0500523 certMsgBytes := certMsg.marshal()
524 if config.Bugs.WrongCertificateMessageType {
525 certMsgBytes[0] += 42
526 }
527 hs.writeServerHash(certMsgBytes)
528 c.writeRecord(recordTypeHandshake, certMsgBytes)
David Benjamin48cae082014-10-27 01:06:24 -0400529 }
David Benjamin1c375dd2014-07-12 00:48:23 -0400530 }
Adam Langley95c29f32014-06-20 12:00:00 -0700531
David Benjamindcd979f2015-04-20 18:26:52 -0400532 if hs.hello.ocspStapling && !c.config.Bugs.SkipCertificateStatus {
Adam Langley95c29f32014-06-20 12:00:00 -0700533 certStatus := new(certificateStatusMsg)
534 certStatus.statusType = statusTypeOCSP
535 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -0400536 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700537 c.writeRecord(recordTypeHandshake, certStatus.marshal())
538 }
539
540 keyAgreement := hs.suite.ka(c.vers)
541 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
542 if err != nil {
543 c.sendAlert(alertHandshakeFailure)
544 return err
545 }
David Benjamin9c651c92014-07-12 13:27:45 -0400546 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -0400547 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700548 c.writeRecord(recordTypeHandshake, skx.marshal())
549 }
550
551 if config.ClientAuth >= RequestClientCert {
552 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -0400553 certReq := &certificateRequestMsg{
554 certificateTypes: config.ClientCertificateTypes,
555 }
556 if certReq.certificateTypes == nil {
557 certReq.certificateTypes = []byte{
558 byte(CertTypeRSASign),
559 byte(CertTypeECDSASign),
560 }
Adam Langley95c29f32014-06-20 12:00:00 -0700561 }
562 if c.vers >= VersionTLS12 {
563 certReq.hasSignatureAndHash = true
David Benjamin000800a2014-11-14 01:43:59 -0500564 if !config.Bugs.NoSignatureAndHashes {
565 certReq.signatureAndHashes = config.signatureAndHashesForServer()
566 }
Adam Langley95c29f32014-06-20 12:00:00 -0700567 }
568
569 // An empty list of certificateAuthorities signals to
570 // the client that it may send any certificate in response
571 // to our request. When we know the CAs we trust, then
572 // we can send them down, so that the client can choose
573 // an appropriate certificate to give to us.
574 if config.ClientCAs != nil {
575 certReq.certificateAuthorities = config.ClientCAs.Subjects()
576 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400577 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700578 c.writeRecord(recordTypeHandshake, certReq.marshal())
579 }
580
581 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400582 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700583 c.writeRecord(recordTypeHandshake, helloDone.marshal())
David Benjamina4e6d482015-03-02 19:10:53 -0500584 c.dtlsFlushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700585
586 var pub crypto.PublicKey // public key for client auth, if any
587
David Benjamin83f90402015-01-27 01:09:43 -0500588 if err := c.simulatePacketLoss(nil); err != nil {
589 return err
590 }
Adam Langley95c29f32014-06-20 12:00:00 -0700591 msg, err := c.readHandshake()
592 if err != nil {
593 return err
594 }
595
596 var ok bool
597 // If we requested a client certificate, then the client must send a
598 // certificate message, even if it's empty.
599 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -0400600 var certMsg *certificateMsg
Adam Langley95c29f32014-06-20 12:00:00 -0700601 if certMsg, ok = msg.(*certificateMsg); !ok {
602 c.sendAlert(alertUnexpectedMessage)
603 return unexpectedMessageError(certMsg, msg)
604 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400605 hs.writeClientHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700606
607 if len(certMsg.certificates) == 0 {
608 // The client didn't actually send a certificate
609 switch config.ClientAuth {
610 case RequireAnyClientCert, RequireAndVerifyClientCert:
611 c.sendAlert(alertBadCertificate)
612 return errors.New("tls: client didn't provide a certificate")
613 }
614 }
615
616 pub, err = hs.processCertsFromClient(certMsg.certificates)
617 if err != nil {
618 return err
619 }
620
621 msg, err = c.readHandshake()
622 if err != nil {
623 return err
624 }
625 }
626
627 // Get client key exchange
628 ckx, ok := msg.(*clientKeyExchangeMsg)
629 if !ok {
630 c.sendAlert(alertUnexpectedMessage)
631 return unexpectedMessageError(ckx, msg)
632 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400633 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700634
David Benjamine098ec22014-08-27 23:13:20 -0400635 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
636 if err != nil {
637 c.sendAlert(alertHandshakeFailure)
638 return err
639 }
Adam Langley75712922014-10-10 16:23:43 -0700640 if c.extendedMasterSecret {
641 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
642 } else {
643 if c.config.Bugs.RequireExtendedMasterSecret {
644 return errors.New("tls: extended master secret required but not supported by peer")
645 }
646 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
647 }
David Benjamine098ec22014-08-27 23:13:20 -0400648
Adam Langley95c29f32014-06-20 12:00:00 -0700649 // If we received a client cert in response to our certificate request message,
650 // the client will send us a certificateVerifyMsg immediately after the
651 // clientKeyExchangeMsg. This message is a digest of all preceding
652 // handshake-layer messages that is signed using the private key corresponding
653 // to the client's certificate. This allows us to verify that the client is in
654 // possession of the private key of the certificate.
655 if len(c.peerCertificates) > 0 {
656 msg, err = c.readHandshake()
657 if err != nil {
658 return err
659 }
660 certVerify, ok := msg.(*certificateVerifyMsg)
661 if !ok {
662 c.sendAlert(alertUnexpectedMessage)
663 return unexpectedMessageError(certVerify, msg)
664 }
665
David Benjaminde620d92014-07-18 15:03:41 -0400666 // Determine the signature type.
667 var signatureAndHash signatureAndHash
668 if certVerify.hasSignatureAndHash {
669 signatureAndHash = certVerify.signatureAndHash
David Benjamin000800a2014-11-14 01:43:59 -0500670 if !isSupportedSignatureAndHash(signatureAndHash, config.signatureAndHashesForServer()) {
671 return errors.New("tls: unsupported hash function for client certificate")
672 }
David Benjaminde620d92014-07-18 15:03:41 -0400673 } else {
674 // Before TLS 1.2 the signature algorithm was implicit
675 // from the key type, and only one hash per signature
676 // algorithm was possible. Leave the hash as zero.
677 switch pub.(type) {
678 case *ecdsa.PublicKey:
679 signatureAndHash.signature = signatureECDSA
680 case *rsa.PublicKey:
681 signatureAndHash.signature = signatureRSA
682 }
683 }
684
Adam Langley95c29f32014-06-20 12:00:00 -0700685 switch key := pub.(type) {
686 case *ecdsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400687 if signatureAndHash.signature != signatureECDSA {
688 err = errors.New("tls: bad signature type for client's ECDSA certificate")
689 break
690 }
Adam Langley95c29f32014-06-20 12:00:00 -0700691 ecdsaSig := new(ecdsaSignature)
692 if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {
693 break
694 }
695 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
696 err = errors.New("ECDSA signature contained zero or negative values")
697 break
698 }
David Benjaminde620d92014-07-18 15:03:41 -0400699 var digest []byte
David Benjamine098ec22014-08-27 23:13:20 -0400700 digest, _, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400701 if err != nil {
702 break
703 }
Adam Langley95c29f32014-06-20 12:00:00 -0700704 if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {
705 err = errors.New("ECDSA verification failure")
706 break
707 }
708 case *rsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400709 if signatureAndHash.signature != signatureRSA {
710 err = errors.New("tls: bad signature type for client's RSA certificate")
711 break
712 }
713 var digest []byte
714 var hashFunc crypto.Hash
David Benjamine098ec22014-08-27 23:13:20 -0400715 digest, hashFunc, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400716 if err != nil {
717 break
718 }
Adam Langley95c29f32014-06-20 12:00:00 -0700719 err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)
720 }
721 if err != nil {
722 c.sendAlert(alertBadCertificate)
723 return errors.New("could not validate signature of connection nonces: " + err.Error())
724 }
725
David Benjamin83c0bc92014-08-04 01:23:53 -0400726 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700727 }
728
David Benjamine098ec22014-08-27 23:13:20 -0400729 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -0700730
731 return nil
732}
733
734func (hs *serverHandshakeState) establishKeys() error {
735 c := hs.c
736
737 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
738 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
739
740 var clientCipher, serverCipher interface{}
741 var clientHash, serverHash macFunction
742
743 if hs.suite.aead == nil {
744 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
745 clientHash = hs.suite.mac(c.vers, clientMAC)
746 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
747 serverHash = hs.suite.mac(c.vers, serverMAC)
748 } else {
749 clientCipher = hs.suite.aead(clientKey, clientIV)
750 serverCipher = hs.suite.aead(serverKey, serverIV)
751 }
752
753 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
754 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
755
756 return nil
757}
758
Adam Langleyaf0e32c2015-06-03 09:57:23 -0700759func (hs *serverHandshakeState) readFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700760 c := hs.c
761
762 c.readRecord(recordTypeChangeCipherSpec)
763 if err := c.in.error(); err != nil {
764 return err
765 }
766
767 if hs.hello.nextProtoNeg {
768 msg, err := c.readHandshake()
769 if err != nil {
770 return err
771 }
772 nextProto, ok := msg.(*nextProtoMsg)
773 if !ok {
774 c.sendAlert(alertUnexpectedMessage)
775 return unexpectedMessageError(nextProto, msg)
776 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400777 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700778 c.clientProtocol = nextProto.proto
779 }
780
David Benjamind30a9902014-08-24 01:44:23 -0400781 if hs.hello.channelIDRequested {
782 msg, err := c.readHandshake()
783 if err != nil {
784 return err
785 }
786 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
787 if !ok {
788 c.sendAlert(alertUnexpectedMessage)
789 return unexpectedMessageError(encryptedExtensions, msg)
790 }
791 x := new(big.Int).SetBytes(encryptedExtensions.channelID[0:32])
792 y := new(big.Int).SetBytes(encryptedExtensions.channelID[32:64])
793 r := new(big.Int).SetBytes(encryptedExtensions.channelID[64:96])
794 s := new(big.Int).SetBytes(encryptedExtensions.channelID[96:128])
795 if !elliptic.P256().IsOnCurve(x, y) {
796 return errors.New("tls: invalid channel ID public key")
797 }
798 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
799 var resumeHash []byte
800 if isResume {
801 resumeHash = hs.sessionState.handshakeHash
802 }
803 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
804 return errors.New("tls: invalid channel ID signature")
805 }
806 c.channelID = channelID
807
808 hs.writeClientHash(encryptedExtensions.marshal())
809 }
810
Adam Langley95c29f32014-06-20 12:00:00 -0700811 msg, err := c.readHandshake()
812 if err != nil {
813 return err
814 }
815 clientFinished, ok := msg.(*finishedMsg)
816 if !ok {
817 c.sendAlert(alertUnexpectedMessage)
818 return unexpectedMessageError(clientFinished, msg)
819 }
820
821 verify := hs.finishedHash.clientSum(hs.masterSecret)
822 if len(verify) != len(clientFinished.verifyData) ||
823 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
824 c.sendAlert(alertHandshakeFailure)
825 return errors.New("tls: client's Finished message is incorrect")
826 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700827 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -0700828 copy(out, clientFinished.verifyData)
Adam Langley95c29f32014-06-20 12:00:00 -0700829
David Benjamin83c0bc92014-08-04 01:23:53 -0400830 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700831 return nil
832}
833
834func (hs *serverHandshakeState) sendSessionTicket() error {
Adam Langley95c29f32014-06-20 12:00:00 -0700835 c := hs.c
Adam Langley95c29f32014-06-20 12:00:00 -0700836 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -0400837 vers: c.vers,
838 cipherSuite: hs.suite.id,
839 masterSecret: hs.masterSecret,
840 certificates: hs.certsFromClient,
841 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -0700842 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500843
844 if !hs.hello.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
845 if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
846 c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
847 }
848 return nil
849 }
850
851 m := new(newSessionTicketMsg)
852
853 var err error
Adam Langley95c29f32014-06-20 12:00:00 -0700854 m.ticket, err = c.encryptTicket(&state)
855 if err != nil {
856 return err
857 }
Adam Langley95c29f32014-06-20 12:00:00 -0700858
David Benjamin83c0bc92014-08-04 01:23:53 -0400859 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700860 c.writeRecord(recordTypeHandshake, m.marshal())
861
862 return nil
863}
864
Adam Langleyaf0e32c2015-06-03 09:57:23 -0700865func (hs *serverHandshakeState) sendFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700866 c := hs.c
867
David Benjamin86271ee2014-07-21 16:14:03 -0400868 finished := new(finishedMsg)
869 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
Adam Langleyaf0e32c2015-06-03 09:57:23 -0700870 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -0400871 if c.config.Bugs.BadFinished {
872 finished.verifyData[0]++
873 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700874 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -0500875 hs.finishedBytes = finished.marshal()
876 hs.writeServerHash(hs.finishedBytes)
877 postCCSBytes := hs.finishedBytes
David Benjamin86271ee2014-07-21 16:14:03 -0400878
879 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
880 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
881 postCCSBytes = postCCSBytes[5:]
882 }
David Benjamina4e6d482015-03-02 19:10:53 -0500883 c.dtlsFlushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -0400884
David Benjamina0e52232014-07-19 17:39:58 -0400885 if !c.config.Bugs.SkipChangeCipherSpec {
886 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
887 }
Adam Langley95c29f32014-06-20 12:00:00 -0700888
David Benjamin4189bd92015-01-25 23:52:39 -0500889 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
890 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
891 }
David Benjamindc3da932015-03-12 15:09:02 -0400892 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
893 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
894 return errors.New("tls: simulating post-CCS alert")
895 }
David Benjamin4189bd92015-01-25 23:52:39 -0500896
David Benjaminb80168e2015-02-08 18:30:14 -0500897 if !c.config.Bugs.SkipFinished {
898 c.writeRecord(recordTypeHandshake, postCCSBytes)
David Benjamina4e6d482015-03-02 19:10:53 -0500899 c.dtlsFlushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -0500900 }
Adam Langley95c29f32014-06-20 12:00:00 -0700901
David Benjaminc565ebb2015-04-03 04:06:36 -0400902 c.cipherSuite = hs.suite
Adam Langley95c29f32014-06-20 12:00:00 -0700903
904 return nil
905}
906
907// processCertsFromClient takes a chain of client certificates either from a
908// Certificates message or from a sessionState and verifies them. It returns
909// the public key of the leaf certificate.
910func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
911 c := hs.c
912
913 hs.certsFromClient = certificates
914 certs := make([]*x509.Certificate, len(certificates))
915 var err error
916 for i, asn1Data := range certificates {
917 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
918 c.sendAlert(alertBadCertificate)
919 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
920 }
921 }
922
923 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
924 opts := x509.VerifyOptions{
925 Roots: c.config.ClientCAs,
926 CurrentTime: c.config.time(),
927 Intermediates: x509.NewCertPool(),
928 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
929 }
930
931 for _, cert := range certs[1:] {
932 opts.Intermediates.AddCert(cert)
933 }
934
935 chains, err := certs[0].Verify(opts)
936 if err != nil {
937 c.sendAlert(alertBadCertificate)
938 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
939 }
940
941 ok := false
942 for _, ku := range certs[0].ExtKeyUsage {
943 if ku == x509.ExtKeyUsageClientAuth {
944 ok = true
945 break
946 }
947 }
948 if !ok {
949 c.sendAlert(alertHandshakeFailure)
950 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
951 }
952
953 c.verifiedChains = chains
954 }
955
956 if len(certs) > 0 {
957 var pub crypto.PublicKey
958 switch key := certs[0].PublicKey.(type) {
959 case *ecdsa.PublicKey, *rsa.PublicKey:
960 pub = key
961 default:
962 c.sendAlert(alertUnsupportedCertificate)
963 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
964 }
965 c.peerCertificates = certs
966 return pub, nil
967 }
968
969 return nil, nil
970}
971
David Benjamin83c0bc92014-08-04 01:23:53 -0400972func (hs *serverHandshakeState) writeServerHash(msg []byte) {
973 // writeServerHash is called before writeRecord.
974 hs.writeHash(msg, hs.c.sendHandshakeSeq)
975}
976
977func (hs *serverHandshakeState) writeClientHash(msg []byte) {
978 // writeClientHash is called after readHandshake.
979 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
980}
981
982func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
983 if hs.c.isDTLS {
984 // This is somewhat hacky. DTLS hashes a slightly different format.
985 // First, the TLS header.
986 hs.finishedHash.Write(msg[:4])
987 // Then the sequence number and reassembled fragment offset (always 0).
988 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
989 // Then the reassembled fragment (always equal to the message length).
990 hs.finishedHash.Write(msg[1:4])
991 // And then the message body.
992 hs.finishedHash.Write(msg[4:])
993 } else {
994 hs.finishedHash.Write(msg)
995 }
996}
997
Adam Langley95c29f32014-06-20 12:00:00 -0700998// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
999// is acceptable to use.
1000func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
1001 for _, supported := range supportedCipherSuites {
1002 if id == supported {
1003 var candidate *cipherSuite
1004
1005 for _, s := range cipherSuites {
1006 if s.id == id {
1007 candidate = s
1008 break
1009 }
1010 }
1011 if candidate == nil {
1012 continue
1013 }
1014 // Don't select a ciphersuite which we can't
1015 // support for this client.
1016 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
1017 continue
1018 }
1019 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
1020 continue
1021 }
David Benjamin39ebf532014-08-31 02:23:49 -04001022 if !c.config.Bugs.SkipCipherVersionCheck && version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
Adam Langley95c29f32014-06-20 12:00:00 -07001023 continue
1024 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001025 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
1026 continue
1027 }
Adam Langley95c29f32014-06-20 12:00:00 -07001028 return candidate
1029 }
1030 }
1031
1032 return nil
1033}