blob: 7686402e9185ab968a89003f7bc6a0692907d5ee [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 }
Adam Langley33ad2b52015-07-20 17:43:53 -0700142 if size := config.Bugs.RequireClientHelloSize; size != 0 && len(hs.clientHello.raw) != size {
143 return false, fmt.Errorf("tls: ClientHello record size is %d, but expected %d", len(hs.clientHello.raw), size)
Feng Lu41aa3252014-11-21 22:47:56 -0800144 }
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
Adam Langley09505632015-07-30 18:10:13 -0700213 hs.hello = &serverHelloMsg {
214 isDTLS: c.isDTLS,
215 customExtension: config.Bugs.CustomExtension,
216 }
Adam Langley95c29f32014-06-20 12:00:00 -0700217
218 supportedCurve := false
219 preferredCurves := config.curvePreferences()
David Benjaminc574f412015-04-20 11:13:01 -0400220 if config.Bugs.IgnorePeerCurvePreferences {
221 hs.clientHello.supportedCurves = preferredCurves
222 }
Adam Langley95c29f32014-06-20 12:00:00 -0700223Curves:
224 for _, curve := range hs.clientHello.supportedCurves {
225 for _, supported := range preferredCurves {
226 if supported == curve {
227 supportedCurve = true
228 break Curves
229 }
230 }
231 }
232
233 supportedPointFormat := false
234 for _, pointFormat := range hs.clientHello.supportedPoints {
235 if pointFormat == pointFormatUncompressed {
236 supportedPointFormat = true
237 break
238 }
239 }
240 hs.ellipticOk = supportedCurve && supportedPointFormat
241
242 foundCompression := false
243 // We only support null compression, so check that the client offered it.
244 for _, compression := range hs.clientHello.compressionMethods {
245 if compression == compressionNone {
246 foundCompression = true
247 break
248 }
249 }
250
251 if !foundCompression {
252 c.sendAlert(alertHandshakeFailure)
253 return false, errors.New("tls: client does not support uncompressed connections")
254 }
255
256 hs.hello.vers = c.vers
257 hs.hello.random = make([]byte, 32)
258 _, err = io.ReadFull(config.rand(), hs.hello.random)
259 if err != nil {
260 c.sendAlert(alertInternalError)
261 return false, err
262 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700263
Adam Langleycf2d4f42014-10-28 19:06:14 -0700264 if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) {
Adam Langley2ae77d22014-10-28 17:29:33 -0700265 c.sendAlert(alertHandshakeFailure)
Adam Langleycf2d4f42014-10-28 19:06:14 -0700266 return false, errors.New("tls: renegotiation mismatch")
Adam Langley2ae77d22014-10-28 17:29:33 -0700267 }
Adam Langleycf2d4f42014-10-28 19:06:14 -0700268
269 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
270 hs.hello.secureRenegotiation = append(hs.hello.secureRenegotiation, c.clientVerify...)
271 hs.hello.secureRenegotiation = append(hs.hello.secureRenegotiation, c.serverVerify...)
272 if c.config.Bugs.BadRenegotiationInfo {
273 hs.hello.secureRenegotiation[0] ^= 0x80
274 }
275 } else {
276 hs.hello.secureRenegotiation = hs.clientHello.secureRenegotiation
277 }
278
David Benjamincff0b902015-05-15 23:09:47 -0400279 if c.config.Bugs.NoRenegotiationInfo {
280 hs.hello.secureRenegotiation = nil
281 }
282
Adam Langley95c29f32014-06-20 12:00:00 -0700283 hs.hello.compressionMethod = compressionNone
David Benjamin35a7a442014-07-05 00:23:20 -0400284 hs.hello.duplicateExtension = c.config.Bugs.DuplicateExtension
Adam Langley95c29f32014-06-20 12:00:00 -0700285 if len(hs.clientHello.serverName) > 0 {
286 c.serverName = hs.clientHello.serverName
287 }
David Benjaminfa055a22014-09-15 16:51:51 -0400288
289 if len(hs.clientHello.alpnProtocols) > 0 {
Adam Langleyefb0e162015-07-09 11:35:04 -0700290 if proto := c.config.Bugs.ALPNProtocol; proto != nil {
291 hs.hello.alpnProtocol = *proto
292 hs.hello.alpnProtocolEmpty = len(*proto) == 0
293 c.clientProtocol = *proto
294 c.usedALPN = true
295 } else if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
David Benjaminfa055a22014-09-15 16:51:51 -0400296 hs.hello.alpnProtocol = selectedProto
297 c.clientProtocol = selectedProto
David Benjaminfc7b0862014-09-06 13:21:53 -0400298 c.usedALPN = true
David Benjaminfa055a22014-09-15 16:51:51 -0400299 }
300 } else {
301 // Although sending an empty NPN extension is reasonable, Firefox has
302 // had a bug around this. Best to send nothing at all if
303 // config.NextProtos is empty. See
304 // https://code.google.com/p/go/issues/detail?id=5445.
305 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
306 hs.hello.nextProtoNeg = true
307 hs.hello.nextProtos = config.NextProtos
308 }
Adam Langley95c29f32014-06-20 12:00:00 -0700309 }
Adam Langley75712922014-10-10 16:23:43 -0700310 hs.hello.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !c.config.Bugs.NoExtendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700311
312 if len(config.Certificates) == 0 {
313 c.sendAlert(alertInternalError)
314 return false, errors.New("tls: no certificates configured")
315 }
316 hs.cert = &config.Certificates[0]
317 if len(hs.clientHello.serverName) > 0 {
318 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
319 }
David Benjamine78bfde2014-09-06 12:45:15 -0400320 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
321 return false, errors.New("tls: unexpected server name")
322 }
Adam Langley95c29f32014-06-20 12:00:00 -0700323
David Benjamind30a9902014-08-24 01:44:23 -0400324 if hs.clientHello.channelIDSupported && config.RequestChannelID {
325 hs.hello.channelIDRequested = true
326 }
327
David Benjaminca6c8262014-11-15 19:06:08 -0500328 if hs.clientHello.srtpProtectionProfiles != nil {
329 SRTPLoop:
330 for _, p1 := range c.config.SRTPProtectionProfiles {
331 for _, p2 := range hs.clientHello.srtpProtectionProfiles {
332 if p1 == p2 {
333 hs.hello.srtpProtectionProfile = p1
334 c.srtpProtectionProfile = p1
335 break SRTPLoop
336 }
337 }
338 }
339 }
340
341 if c.config.Bugs.SendSRTPProtectionProfile != 0 {
342 hs.hello.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
343 }
344
Adam Langley09505632015-07-30 18:10:13 -0700345 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
346 if hs.clientHello.customExtension != *expected {
347 return false, fmt.Errorf("tls: bad custom extension contents %q", hs.clientHello.customExtension)
348 }
349 }
350
Adam Langley95c29f32014-06-20 12:00:00 -0700351 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
352
David Benjamin4b27d9f2015-05-12 22:42:52 -0400353 // For test purposes, check that the peer never offers a session when
354 // renegotiating.
355 if c.cipherSuite != nil && len(hs.clientHello.sessionId) > 0 && c.config.Bugs.FailIfResumeOnRenego {
356 return false, errors.New("tls: offered resumption on renegotiation")
357 }
358
Adam Langley95c29f32014-06-20 12:00:00 -0700359 if hs.checkForResumption() {
360 return true, nil
361 }
362
Adam Langleyac61fa32014-06-23 12:03:11 -0700363 var scsvFound bool
364
365 for _, cipherSuite := range hs.clientHello.cipherSuites {
366 if cipherSuite == fallbackSCSV {
367 scsvFound = true
368 break
369 }
370 }
371
372 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
373 return false, errors.New("tls: no fallback SCSV found when expected")
374 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
375 return false, errors.New("tls: fallback SCSV found when not expected")
376 }
377
David Benjamin67d1fb52015-03-16 15:16:23 -0400378 if config.Bugs.IgnorePeerCipherPreferences {
379 hs.clientHello.cipherSuites = c.config.cipherSuites()
380 }
Adam Langley95c29f32014-06-20 12:00:00 -0700381 var preferenceList, supportedList []uint16
382 if c.config.PreferServerCipherSuites {
383 preferenceList = c.config.cipherSuites()
384 supportedList = hs.clientHello.cipherSuites
385 } else {
386 preferenceList = hs.clientHello.cipherSuites
387 supportedList = c.config.cipherSuites()
388 }
389
390 for _, id := range preferenceList {
391 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
392 break
393 }
394 }
395
396 if hs.suite == nil {
397 c.sendAlert(alertHandshakeFailure)
398 return false, errors.New("tls: no cipher suite supported by both client and server")
399 }
400
401 return false, nil
402}
403
404// checkForResumption returns true if we should perform resumption on this connection.
405func (hs *serverHandshakeState) checkForResumption() bool {
406 c := hs.c
407
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500408 if len(hs.clientHello.sessionTicket) > 0 {
409 if c.config.SessionTicketsDisabled {
410 return false
411 }
David Benjaminb0c8db72014-09-24 15:19:56 -0400412
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500413 var ok bool
414 if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
415 return false
416 }
417 } else {
418 if c.config.ServerSessionCache == nil {
419 return false
420 }
421
422 var ok bool
423 sessionId := string(hs.clientHello.sessionId)
424 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
425 return false
426 }
Adam Langley95c29f32014-06-20 12:00:00 -0700427 }
428
David Benjamine18d8212014-11-10 02:37:15 -0500429 // Never resume a session for a different SSL version.
430 if !c.config.Bugs.AllowSessionVersionMismatch && c.vers != hs.sessionState.vers {
431 return false
Adam Langley95c29f32014-06-20 12:00:00 -0700432 }
433
434 cipherSuiteOk := false
435 // Check that the client is still offering the ciphersuite in the session.
436 for _, id := range hs.clientHello.cipherSuites {
437 if id == hs.sessionState.cipherSuite {
438 cipherSuiteOk = true
439 break
440 }
441 }
442 if !cipherSuiteOk {
443 return false
444 }
445
446 // Check that we also support the ciphersuite from the session.
447 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk)
448 if hs.suite == nil {
449 return false
450 }
451
452 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
453 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
454 if needClientCerts && !sessionHasClientCerts {
455 return false
456 }
457 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
458 return false
459 }
460
461 return true
462}
463
464func (hs *serverHandshakeState) doResumeHandshake() error {
465 c := hs.c
466
467 hs.hello.cipherSuite = hs.suite.id
David Benjaminece3de92015-03-16 18:02:20 -0400468 if c.config.Bugs.SendCipherSuite != 0 {
469 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
470 }
Adam Langley95c29f32014-06-20 12:00:00 -0700471 // We echo the client's session ID in the ServerHello to let it know
472 // that we're doing a resumption.
473 hs.hello.sessionId = hs.clientHello.sessionId
David Benjaminbed9aae2014-08-07 19:13:38 -0400474 hs.hello.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -0700475
476 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -0400477 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -0400478 hs.writeClientHash(hs.clientHello.marshal())
479 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700480
481 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
482
483 if len(hs.sessionState.certificates) > 0 {
484 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
485 return err
486 }
487 }
488
489 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -0700490 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700491
492 return nil
493}
494
495func (hs *serverHandshakeState) doFullHandshake() error {
496 config := hs.c.config
497 c := hs.c
498
David Benjamin48cae082014-10-27 01:06:24 -0400499 isPSK := hs.suite.flags&suitePSK != 0
500 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700501 hs.hello.ocspStapling = true
502 }
503
David Benjamin61f95272014-11-25 01:55:35 -0500504 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
505 hs.hello.sctList = hs.cert.SignedCertificateTimestampList
506 }
507
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500508 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
Adam Langley95c29f32014-06-20 12:00:00 -0700509 hs.hello.cipherSuite = hs.suite.id
David Benjamin6095de82014-12-27 01:50:38 -0500510 if config.Bugs.SendCipherSuite != 0 {
511 hs.hello.cipherSuite = config.Bugs.SendCipherSuite
512 }
Adam Langley75712922014-10-10 16:23:43 -0700513 c.extendedMasterSecret = hs.hello.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700514
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500515 // Generate a session ID if we're to save the session.
516 if !hs.hello.ticketSupported && config.ServerSessionCache != nil {
517 hs.hello.sessionId = make([]byte, 32)
518 if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
519 c.sendAlert(alertInternalError)
520 return errors.New("tls: short read from Rand: " + err.Error())
521 }
522 }
523
Adam Langley95c29f32014-06-20 12:00:00 -0700524 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400525 hs.writeClientHash(hs.clientHello.marshal())
526 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700527
528 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
529
David Benjamin48cae082014-10-27 01:06:24 -0400530 if !isPSK {
531 certMsg := new(certificateMsg)
David Benjamin8923c0b2015-06-07 11:42:34 -0400532 if !config.Bugs.EmptyCertificateList {
533 certMsg.certificates = hs.cert.Certificate
534 }
David Benjamin48cae082014-10-27 01:06:24 -0400535 if !config.Bugs.UnauthenticatedECDH {
David Benjaminbcb2d912015-02-24 23:45:43 -0500536 certMsgBytes := certMsg.marshal()
537 if config.Bugs.WrongCertificateMessageType {
538 certMsgBytes[0] += 42
539 }
540 hs.writeServerHash(certMsgBytes)
541 c.writeRecord(recordTypeHandshake, certMsgBytes)
David Benjamin48cae082014-10-27 01:06:24 -0400542 }
David Benjamin1c375dd2014-07-12 00:48:23 -0400543 }
Adam Langley95c29f32014-06-20 12:00:00 -0700544
David Benjamindcd979f2015-04-20 18:26:52 -0400545 if hs.hello.ocspStapling && !c.config.Bugs.SkipCertificateStatus {
Adam Langley95c29f32014-06-20 12:00:00 -0700546 certStatus := new(certificateStatusMsg)
547 certStatus.statusType = statusTypeOCSP
548 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -0400549 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700550 c.writeRecord(recordTypeHandshake, certStatus.marshal())
551 }
552
553 keyAgreement := hs.suite.ka(c.vers)
554 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
555 if err != nil {
556 c.sendAlert(alertHandshakeFailure)
557 return err
558 }
David Benjamin9c651c92014-07-12 13:27:45 -0400559 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -0400560 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700561 c.writeRecord(recordTypeHandshake, skx.marshal())
562 }
563
564 if config.ClientAuth >= RequestClientCert {
565 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -0400566 certReq := &certificateRequestMsg{
567 certificateTypes: config.ClientCertificateTypes,
568 }
569 if certReq.certificateTypes == nil {
570 certReq.certificateTypes = []byte{
571 byte(CertTypeRSASign),
572 byte(CertTypeECDSASign),
573 }
Adam Langley95c29f32014-06-20 12:00:00 -0700574 }
575 if c.vers >= VersionTLS12 {
576 certReq.hasSignatureAndHash = true
David Benjamin000800a2014-11-14 01:43:59 -0500577 if !config.Bugs.NoSignatureAndHashes {
578 certReq.signatureAndHashes = config.signatureAndHashesForServer()
579 }
Adam Langley95c29f32014-06-20 12:00:00 -0700580 }
581
582 // An empty list of certificateAuthorities signals to
583 // the client that it may send any certificate in response
584 // to our request. When we know the CAs we trust, then
585 // we can send them down, so that the client can choose
586 // an appropriate certificate to give to us.
587 if config.ClientCAs != nil {
588 certReq.certificateAuthorities = config.ClientCAs.Subjects()
589 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400590 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700591 c.writeRecord(recordTypeHandshake, certReq.marshal())
592 }
593
594 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400595 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700596 c.writeRecord(recordTypeHandshake, helloDone.marshal())
David Benjamina4e6d482015-03-02 19:10:53 -0500597 c.dtlsFlushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700598
599 var pub crypto.PublicKey // public key for client auth, if any
600
David Benjamin83f90402015-01-27 01:09:43 -0500601 if err := c.simulatePacketLoss(nil); err != nil {
602 return err
603 }
Adam Langley95c29f32014-06-20 12:00:00 -0700604 msg, err := c.readHandshake()
605 if err != nil {
606 return err
607 }
608
609 var ok bool
610 // If we requested a client certificate, then the client must send a
611 // certificate message, even if it's empty.
612 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -0400613 var certMsg *certificateMsg
Adam Langley95c29f32014-06-20 12:00:00 -0700614 if certMsg, ok = msg.(*certificateMsg); !ok {
615 c.sendAlert(alertUnexpectedMessage)
616 return unexpectedMessageError(certMsg, msg)
617 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400618 hs.writeClientHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700619
620 if len(certMsg.certificates) == 0 {
621 // The client didn't actually send a certificate
622 switch config.ClientAuth {
623 case RequireAnyClientCert, RequireAndVerifyClientCert:
624 c.sendAlert(alertBadCertificate)
625 return errors.New("tls: client didn't provide a certificate")
626 }
627 }
628
629 pub, err = hs.processCertsFromClient(certMsg.certificates)
630 if err != nil {
631 return err
632 }
633
634 msg, err = c.readHandshake()
635 if err != nil {
636 return err
637 }
638 }
639
640 // Get client key exchange
641 ckx, ok := msg.(*clientKeyExchangeMsg)
642 if !ok {
643 c.sendAlert(alertUnexpectedMessage)
644 return unexpectedMessageError(ckx, msg)
645 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400646 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700647
David Benjamine098ec22014-08-27 23:13:20 -0400648 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
649 if err != nil {
650 c.sendAlert(alertHandshakeFailure)
651 return err
652 }
Adam Langley75712922014-10-10 16:23:43 -0700653 if c.extendedMasterSecret {
654 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
655 } else {
656 if c.config.Bugs.RequireExtendedMasterSecret {
657 return errors.New("tls: extended master secret required but not supported by peer")
658 }
659 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
660 }
David Benjamine098ec22014-08-27 23:13:20 -0400661
Adam Langley95c29f32014-06-20 12:00:00 -0700662 // If we received a client cert in response to our certificate request message,
663 // the client will send us a certificateVerifyMsg immediately after the
664 // clientKeyExchangeMsg. This message is a digest of all preceding
665 // handshake-layer messages that is signed using the private key corresponding
666 // to the client's certificate. This allows us to verify that the client is in
667 // possession of the private key of the certificate.
668 if len(c.peerCertificates) > 0 {
669 msg, err = c.readHandshake()
670 if err != nil {
671 return err
672 }
673 certVerify, ok := msg.(*certificateVerifyMsg)
674 if !ok {
675 c.sendAlert(alertUnexpectedMessage)
676 return unexpectedMessageError(certVerify, msg)
677 }
678
David Benjaminde620d92014-07-18 15:03:41 -0400679 // Determine the signature type.
680 var signatureAndHash signatureAndHash
681 if certVerify.hasSignatureAndHash {
682 signatureAndHash = certVerify.signatureAndHash
David Benjamin000800a2014-11-14 01:43:59 -0500683 if !isSupportedSignatureAndHash(signatureAndHash, config.signatureAndHashesForServer()) {
684 return errors.New("tls: unsupported hash function for client certificate")
685 }
David Benjaminde620d92014-07-18 15:03:41 -0400686 } else {
687 // Before TLS 1.2 the signature algorithm was implicit
688 // from the key type, and only one hash per signature
689 // algorithm was possible. Leave the hash as zero.
690 switch pub.(type) {
691 case *ecdsa.PublicKey:
692 signatureAndHash.signature = signatureECDSA
693 case *rsa.PublicKey:
694 signatureAndHash.signature = signatureRSA
695 }
696 }
697
Adam Langley95c29f32014-06-20 12:00:00 -0700698 switch key := pub.(type) {
699 case *ecdsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400700 if signatureAndHash.signature != signatureECDSA {
701 err = errors.New("tls: bad signature type for client's ECDSA certificate")
702 break
703 }
Adam Langley95c29f32014-06-20 12:00:00 -0700704 ecdsaSig := new(ecdsaSignature)
705 if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {
706 break
707 }
708 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
709 err = errors.New("ECDSA signature contained zero or negative values")
710 break
711 }
David Benjaminde620d92014-07-18 15:03:41 -0400712 var digest []byte
David Benjamine098ec22014-08-27 23:13:20 -0400713 digest, _, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400714 if err != nil {
715 break
716 }
Adam Langley95c29f32014-06-20 12:00:00 -0700717 if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {
718 err = errors.New("ECDSA verification failure")
719 break
720 }
721 case *rsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400722 if signatureAndHash.signature != signatureRSA {
723 err = errors.New("tls: bad signature type for client's RSA certificate")
724 break
725 }
726 var digest []byte
727 var hashFunc crypto.Hash
David Benjamine098ec22014-08-27 23:13:20 -0400728 digest, hashFunc, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400729 if err != nil {
730 break
731 }
Adam Langley95c29f32014-06-20 12:00:00 -0700732 err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)
733 }
734 if err != nil {
735 c.sendAlert(alertBadCertificate)
736 return errors.New("could not validate signature of connection nonces: " + err.Error())
737 }
738
David Benjamin83c0bc92014-08-04 01:23:53 -0400739 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700740 }
741
David Benjamine098ec22014-08-27 23:13:20 -0400742 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -0700743
744 return nil
745}
746
747func (hs *serverHandshakeState) establishKeys() error {
748 c := hs.c
749
750 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
751 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
752
753 var clientCipher, serverCipher interface{}
754 var clientHash, serverHash macFunction
755
756 if hs.suite.aead == nil {
757 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
758 clientHash = hs.suite.mac(c.vers, clientMAC)
759 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
760 serverHash = hs.suite.mac(c.vers, serverMAC)
761 } else {
762 clientCipher = hs.suite.aead(clientKey, clientIV)
763 serverCipher = hs.suite.aead(serverKey, serverIV)
764 }
765
766 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
767 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
768
769 return nil
770}
771
Adam Langleyaf0e32c2015-06-03 09:57:23 -0700772func (hs *serverHandshakeState) readFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700773 c := hs.c
774
775 c.readRecord(recordTypeChangeCipherSpec)
776 if err := c.in.error(); err != nil {
777 return err
778 }
779
780 if hs.hello.nextProtoNeg {
781 msg, err := c.readHandshake()
782 if err != nil {
783 return err
784 }
785 nextProto, ok := msg.(*nextProtoMsg)
786 if !ok {
787 c.sendAlert(alertUnexpectedMessage)
788 return unexpectedMessageError(nextProto, msg)
789 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400790 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700791 c.clientProtocol = nextProto.proto
792 }
793
David Benjamind30a9902014-08-24 01:44:23 -0400794 if hs.hello.channelIDRequested {
795 msg, err := c.readHandshake()
796 if err != nil {
797 return err
798 }
799 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
800 if !ok {
801 c.sendAlert(alertUnexpectedMessage)
802 return unexpectedMessageError(encryptedExtensions, msg)
803 }
804 x := new(big.Int).SetBytes(encryptedExtensions.channelID[0:32])
805 y := new(big.Int).SetBytes(encryptedExtensions.channelID[32:64])
806 r := new(big.Int).SetBytes(encryptedExtensions.channelID[64:96])
807 s := new(big.Int).SetBytes(encryptedExtensions.channelID[96:128])
808 if !elliptic.P256().IsOnCurve(x, y) {
809 return errors.New("tls: invalid channel ID public key")
810 }
811 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
812 var resumeHash []byte
813 if isResume {
814 resumeHash = hs.sessionState.handshakeHash
815 }
816 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
817 return errors.New("tls: invalid channel ID signature")
818 }
819 c.channelID = channelID
820
821 hs.writeClientHash(encryptedExtensions.marshal())
822 }
823
Adam Langley95c29f32014-06-20 12:00:00 -0700824 msg, err := c.readHandshake()
825 if err != nil {
826 return err
827 }
828 clientFinished, ok := msg.(*finishedMsg)
829 if !ok {
830 c.sendAlert(alertUnexpectedMessage)
831 return unexpectedMessageError(clientFinished, msg)
832 }
833
834 verify := hs.finishedHash.clientSum(hs.masterSecret)
835 if len(verify) != len(clientFinished.verifyData) ||
836 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
837 c.sendAlert(alertHandshakeFailure)
838 return errors.New("tls: client's Finished message is incorrect")
839 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700840 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -0700841 copy(out, clientFinished.verifyData)
Adam Langley95c29f32014-06-20 12:00:00 -0700842
David Benjamin83c0bc92014-08-04 01:23:53 -0400843 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700844 return nil
845}
846
847func (hs *serverHandshakeState) sendSessionTicket() error {
Adam Langley95c29f32014-06-20 12:00:00 -0700848 c := hs.c
Adam Langley95c29f32014-06-20 12:00:00 -0700849 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -0400850 vers: c.vers,
851 cipherSuite: hs.suite.id,
852 masterSecret: hs.masterSecret,
853 certificates: hs.certsFromClient,
854 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -0700855 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500856
857 if !hs.hello.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
858 if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
859 c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
860 }
861 return nil
862 }
863
864 m := new(newSessionTicketMsg)
865
866 var err error
Adam Langley95c29f32014-06-20 12:00:00 -0700867 m.ticket, err = c.encryptTicket(&state)
868 if err != nil {
869 return err
870 }
Adam Langley95c29f32014-06-20 12:00:00 -0700871
David Benjamin83c0bc92014-08-04 01:23:53 -0400872 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700873 c.writeRecord(recordTypeHandshake, m.marshal())
874
875 return nil
876}
877
Adam Langleyaf0e32c2015-06-03 09:57:23 -0700878func (hs *serverHandshakeState) sendFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700879 c := hs.c
880
David Benjamin86271ee2014-07-21 16:14:03 -0400881 finished := new(finishedMsg)
882 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
Adam Langleyaf0e32c2015-06-03 09:57:23 -0700883 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -0400884 if c.config.Bugs.BadFinished {
885 finished.verifyData[0]++
886 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700887 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -0500888 hs.finishedBytes = finished.marshal()
889 hs.writeServerHash(hs.finishedBytes)
890 postCCSBytes := hs.finishedBytes
David Benjamin86271ee2014-07-21 16:14:03 -0400891
892 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
893 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
894 postCCSBytes = postCCSBytes[5:]
895 }
David Benjamina4e6d482015-03-02 19:10:53 -0500896 c.dtlsFlushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -0400897
David Benjamina0e52232014-07-19 17:39:58 -0400898 if !c.config.Bugs.SkipChangeCipherSpec {
899 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
900 }
Adam Langley95c29f32014-06-20 12:00:00 -0700901
David Benjamin4189bd92015-01-25 23:52:39 -0500902 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
903 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
904 }
David Benjamindc3da932015-03-12 15:09:02 -0400905 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
906 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
907 return errors.New("tls: simulating post-CCS alert")
908 }
David Benjamin4189bd92015-01-25 23:52:39 -0500909
David Benjaminb80168e2015-02-08 18:30:14 -0500910 if !c.config.Bugs.SkipFinished {
911 c.writeRecord(recordTypeHandshake, postCCSBytes)
David Benjamina4e6d482015-03-02 19:10:53 -0500912 c.dtlsFlushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -0500913 }
Adam Langley95c29f32014-06-20 12:00:00 -0700914
David Benjaminc565ebb2015-04-03 04:06:36 -0400915 c.cipherSuite = hs.suite
Adam Langley95c29f32014-06-20 12:00:00 -0700916
917 return nil
918}
919
920// processCertsFromClient takes a chain of client certificates either from a
921// Certificates message or from a sessionState and verifies them. It returns
922// the public key of the leaf certificate.
923func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
924 c := hs.c
925
926 hs.certsFromClient = certificates
927 certs := make([]*x509.Certificate, len(certificates))
928 var err error
929 for i, asn1Data := range certificates {
930 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
931 c.sendAlert(alertBadCertificate)
932 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
933 }
934 }
935
936 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
937 opts := x509.VerifyOptions{
938 Roots: c.config.ClientCAs,
939 CurrentTime: c.config.time(),
940 Intermediates: x509.NewCertPool(),
941 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
942 }
943
944 for _, cert := range certs[1:] {
945 opts.Intermediates.AddCert(cert)
946 }
947
948 chains, err := certs[0].Verify(opts)
949 if err != nil {
950 c.sendAlert(alertBadCertificate)
951 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
952 }
953
954 ok := false
955 for _, ku := range certs[0].ExtKeyUsage {
956 if ku == x509.ExtKeyUsageClientAuth {
957 ok = true
958 break
959 }
960 }
961 if !ok {
962 c.sendAlert(alertHandshakeFailure)
963 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
964 }
965
966 c.verifiedChains = chains
967 }
968
969 if len(certs) > 0 {
970 var pub crypto.PublicKey
971 switch key := certs[0].PublicKey.(type) {
972 case *ecdsa.PublicKey, *rsa.PublicKey:
973 pub = key
974 default:
975 c.sendAlert(alertUnsupportedCertificate)
976 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
977 }
978 c.peerCertificates = certs
979 return pub, nil
980 }
981
982 return nil, nil
983}
984
David Benjamin83c0bc92014-08-04 01:23:53 -0400985func (hs *serverHandshakeState) writeServerHash(msg []byte) {
986 // writeServerHash is called before writeRecord.
987 hs.writeHash(msg, hs.c.sendHandshakeSeq)
988}
989
990func (hs *serverHandshakeState) writeClientHash(msg []byte) {
991 // writeClientHash is called after readHandshake.
992 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
993}
994
995func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
996 if hs.c.isDTLS {
997 // This is somewhat hacky. DTLS hashes a slightly different format.
998 // First, the TLS header.
999 hs.finishedHash.Write(msg[:4])
1000 // Then the sequence number and reassembled fragment offset (always 0).
1001 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1002 // Then the reassembled fragment (always equal to the message length).
1003 hs.finishedHash.Write(msg[1:4])
1004 // And then the message body.
1005 hs.finishedHash.Write(msg[4:])
1006 } else {
1007 hs.finishedHash.Write(msg)
1008 }
1009}
1010
Adam Langley95c29f32014-06-20 12:00:00 -07001011// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
1012// is acceptable to use.
1013func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
1014 for _, supported := range supportedCipherSuites {
1015 if id == supported {
1016 var candidate *cipherSuite
1017
1018 for _, s := range cipherSuites {
1019 if s.id == id {
1020 candidate = s
1021 break
1022 }
1023 }
1024 if candidate == nil {
1025 continue
1026 }
1027 // Don't select a ciphersuite which we can't
1028 // support for this client.
1029 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
1030 continue
1031 }
1032 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
1033 continue
1034 }
David Benjamin39ebf532014-08-31 02:23:49 -04001035 if !c.config.Bugs.SkipCipherVersionCheck && version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
Adam Langley95c29f32014-06-20 12:00:00 -07001036 continue
1037 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001038 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
1039 continue
1040 }
Adam Langley95c29f32014-06-20 12:00:00 -07001041 return candidate
1042 }
1043 }
1044
1045 return nil
1046}