blob: 9647715d4f249e587278e949c40474649e44f265 [file] [log] [blame]
Adam Langley95c29f32014-06-20 12:00:00 -07001// Copyright 2009 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
Adam Langleydc7e9c42015-09-29 15:21:04 -07005package runner
Adam Langley95c29f32014-06-20 12:00:00 -07006
7import (
David Benjamin83c0bc92014-08-04 01:23:53 -04008 "bytes"
Adam Langley95c29f32014-06-20 12:00:00 -07009 "crypto"
10 "crypto/ecdsa"
David Benjamind30a9902014-08-24 01:44:23 -040011 "crypto/elliptic"
Adam Langley95c29f32014-06-20 12:00:00 -070012 "crypto/rsa"
13 "crypto/subtle"
14 "crypto/x509"
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
David Benjamin399e7c92015-07-30 23:01:27 -0400213 hs.hello = &serverHelloMsg{
214 isDTLS: c.isDTLS,
Adam Langley09505632015-07-30 18:10:13 -0700215 customExtension: config.Bugs.CustomExtension,
David Benjamin76c2efc2015-08-31 14:24:29 -0400216 npnLast: config.Bugs.SwapNPNAndALPN,
Adam Langley09505632015-07-30 18:10:13 -0700217 }
Adam Langley95c29f32014-06-20 12:00:00 -0700218
219 supportedCurve := false
220 preferredCurves := config.curvePreferences()
David Benjaminc574f412015-04-20 11:13:01 -0400221 if config.Bugs.IgnorePeerCurvePreferences {
222 hs.clientHello.supportedCurves = preferredCurves
223 }
Adam Langley95c29f32014-06-20 12:00:00 -0700224Curves:
225 for _, curve := range hs.clientHello.supportedCurves {
226 for _, supported := range preferredCurves {
227 if supported == curve {
228 supportedCurve = true
229 break Curves
230 }
231 }
232 }
233
234 supportedPointFormat := false
235 for _, pointFormat := range hs.clientHello.supportedPoints {
236 if pointFormat == pointFormatUncompressed {
237 supportedPointFormat = true
238 break
239 }
240 }
241 hs.ellipticOk = supportedCurve && supportedPointFormat
242
243 foundCompression := false
244 // We only support null compression, so check that the client offered it.
245 for _, compression := range hs.clientHello.compressionMethods {
246 if compression == compressionNone {
247 foundCompression = true
248 break
249 }
250 }
251
252 if !foundCompression {
253 c.sendAlert(alertHandshakeFailure)
254 return false, errors.New("tls: client does not support uncompressed connections")
255 }
256
257 hs.hello.vers = c.vers
258 hs.hello.random = make([]byte, 32)
259 _, err = io.ReadFull(config.rand(), hs.hello.random)
260 if err != nil {
261 c.sendAlert(alertInternalError)
262 return false, err
263 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700264
Adam Langleycf2d4f42014-10-28 19:06:14 -0700265 if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) {
Adam Langley2ae77d22014-10-28 17:29:33 -0700266 c.sendAlert(alertHandshakeFailure)
Adam Langleycf2d4f42014-10-28 19:06:14 -0700267 return false, errors.New("tls: renegotiation mismatch")
Adam Langley2ae77d22014-10-28 17:29:33 -0700268 }
Adam Langleycf2d4f42014-10-28 19:06:14 -0700269
270 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
271 hs.hello.secureRenegotiation = append(hs.hello.secureRenegotiation, c.clientVerify...)
272 hs.hello.secureRenegotiation = append(hs.hello.secureRenegotiation, c.serverVerify...)
273 if c.config.Bugs.BadRenegotiationInfo {
274 hs.hello.secureRenegotiation[0] ^= 0x80
275 }
276 } else {
277 hs.hello.secureRenegotiation = hs.clientHello.secureRenegotiation
278 }
279
David Benjamincff0b902015-05-15 23:09:47 -0400280 if c.config.Bugs.NoRenegotiationInfo {
281 hs.hello.secureRenegotiation = nil
282 }
283
Adam Langley95c29f32014-06-20 12:00:00 -0700284 hs.hello.compressionMethod = compressionNone
David Benjamin35a7a442014-07-05 00:23:20 -0400285 hs.hello.duplicateExtension = c.config.Bugs.DuplicateExtension
Adam Langley95c29f32014-06-20 12:00:00 -0700286 if len(hs.clientHello.serverName) > 0 {
287 c.serverName = hs.clientHello.serverName
288 }
David Benjaminfa055a22014-09-15 16:51:51 -0400289
290 if len(hs.clientHello.alpnProtocols) > 0 {
Adam Langleyefb0e162015-07-09 11:35:04 -0700291 if proto := c.config.Bugs.ALPNProtocol; proto != nil {
292 hs.hello.alpnProtocol = *proto
293 hs.hello.alpnProtocolEmpty = len(*proto) == 0
294 c.clientProtocol = *proto
295 c.usedALPN = true
296 } else if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
David Benjaminfa055a22014-09-15 16:51:51 -0400297 hs.hello.alpnProtocol = selectedProto
298 c.clientProtocol = selectedProto
David Benjaminfc7b0862014-09-06 13:21:53 -0400299 c.usedALPN = true
David Benjaminfa055a22014-09-15 16:51:51 -0400300 }
David Benjamin76c2efc2015-08-31 14:24:29 -0400301 }
302 if len(hs.clientHello.alpnProtocols) == 0 || c.config.Bugs.NegotiateALPNAndNPN {
David Benjaminfa055a22014-09-15 16:51:51 -0400303 // Although sending an empty NPN extension is reasonable, Firefox has
304 // had a bug around this. Best to send nothing at all if
305 // config.NextProtos is empty. See
306 // https://code.google.com/p/go/issues/detail?id=5445.
307 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
308 hs.hello.nextProtoNeg = true
309 hs.hello.nextProtos = config.NextProtos
310 }
Adam Langley95c29f32014-06-20 12:00:00 -0700311 }
Adam Langley75712922014-10-10 16:23:43 -0700312 hs.hello.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !c.config.Bugs.NoExtendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700313
314 if len(config.Certificates) == 0 {
315 c.sendAlert(alertInternalError)
316 return false, errors.New("tls: no certificates configured")
317 }
318 hs.cert = &config.Certificates[0]
319 if len(hs.clientHello.serverName) > 0 {
320 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
321 }
David Benjamine78bfde2014-09-06 12:45:15 -0400322 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
323 return false, errors.New("tls: unexpected server name")
324 }
Adam Langley95c29f32014-06-20 12:00:00 -0700325
David Benjamind30a9902014-08-24 01:44:23 -0400326 if hs.clientHello.channelIDSupported && config.RequestChannelID {
327 hs.hello.channelIDRequested = true
328 }
329
David Benjaminca6c8262014-11-15 19:06:08 -0500330 if hs.clientHello.srtpProtectionProfiles != nil {
331 SRTPLoop:
332 for _, p1 := range c.config.SRTPProtectionProfiles {
333 for _, p2 := range hs.clientHello.srtpProtectionProfiles {
334 if p1 == p2 {
335 hs.hello.srtpProtectionProfile = p1
336 c.srtpProtectionProfile = p1
337 break SRTPLoop
338 }
339 }
340 }
341 }
342
343 if c.config.Bugs.SendSRTPProtectionProfile != 0 {
344 hs.hello.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
345 }
346
Adam Langley09505632015-07-30 18:10:13 -0700347 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
348 if hs.clientHello.customExtension != *expected {
349 return false, fmt.Errorf("tls: bad custom extension contents %q", hs.clientHello.customExtension)
350 }
351 }
352
Adam Langley95c29f32014-06-20 12:00:00 -0700353 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
354
David Benjamin4b27d9f2015-05-12 22:42:52 -0400355 // For test purposes, check that the peer never offers a session when
356 // renegotiating.
357 if c.cipherSuite != nil && len(hs.clientHello.sessionId) > 0 && c.config.Bugs.FailIfResumeOnRenego {
358 return false, errors.New("tls: offered resumption on renegotiation")
359 }
360
David Benjamindd6fed92015-10-23 17:41:12 -0400361 if c.config.Bugs.FailIfSessionOffered && (len(hs.clientHello.sessionTicket) > 0 || len(hs.clientHello.sessionId) > 0) {
362 return false, errors.New("tls: client offered a session ticket or ID")
363 }
364
Adam Langley95c29f32014-06-20 12:00:00 -0700365 if hs.checkForResumption() {
366 return true, nil
367 }
368
Adam Langleyac61fa32014-06-23 12:03:11 -0700369 var scsvFound bool
370
371 for _, cipherSuite := range hs.clientHello.cipherSuites {
372 if cipherSuite == fallbackSCSV {
373 scsvFound = true
374 break
375 }
376 }
377
378 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
379 return false, errors.New("tls: no fallback SCSV found when expected")
380 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
381 return false, errors.New("tls: fallback SCSV found when not expected")
382 }
383
David Benjamin67d1fb52015-03-16 15:16:23 -0400384 if config.Bugs.IgnorePeerCipherPreferences {
385 hs.clientHello.cipherSuites = c.config.cipherSuites()
386 }
Adam Langley95c29f32014-06-20 12:00:00 -0700387 var preferenceList, supportedList []uint16
388 if c.config.PreferServerCipherSuites {
389 preferenceList = c.config.cipherSuites()
390 supportedList = hs.clientHello.cipherSuites
391 } else {
392 preferenceList = hs.clientHello.cipherSuites
393 supportedList = c.config.cipherSuites()
394 }
395
396 for _, id := range preferenceList {
397 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
398 break
399 }
400 }
401
402 if hs.suite == nil {
403 c.sendAlert(alertHandshakeFailure)
404 return false, errors.New("tls: no cipher suite supported by both client and server")
405 }
406
407 return false, nil
408}
409
410// checkForResumption returns true if we should perform resumption on this connection.
411func (hs *serverHandshakeState) checkForResumption() bool {
412 c := hs.c
413
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500414 if len(hs.clientHello.sessionTicket) > 0 {
415 if c.config.SessionTicketsDisabled {
416 return false
417 }
David Benjaminb0c8db72014-09-24 15:19:56 -0400418
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500419 var ok bool
420 if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
421 return false
422 }
423 } else {
424 if c.config.ServerSessionCache == nil {
425 return false
426 }
427
428 var ok bool
429 sessionId := string(hs.clientHello.sessionId)
430 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
431 return false
432 }
Adam Langley95c29f32014-06-20 12:00:00 -0700433 }
434
David Benjamine18d8212014-11-10 02:37:15 -0500435 // Never resume a session for a different SSL version.
436 if !c.config.Bugs.AllowSessionVersionMismatch && c.vers != hs.sessionState.vers {
437 return false
Adam Langley95c29f32014-06-20 12:00:00 -0700438 }
439
440 cipherSuiteOk := false
441 // Check that the client is still offering the ciphersuite in the session.
442 for _, id := range hs.clientHello.cipherSuites {
443 if id == hs.sessionState.cipherSuite {
444 cipherSuiteOk = true
445 break
446 }
447 }
448 if !cipherSuiteOk {
449 return false
450 }
451
452 // Check that we also support the ciphersuite from the session.
453 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk)
454 if hs.suite == nil {
455 return false
456 }
457
458 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
459 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
460 if needClientCerts && !sessionHasClientCerts {
461 return false
462 }
463 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
464 return false
465 }
466
467 return true
468}
469
470func (hs *serverHandshakeState) doResumeHandshake() error {
471 c := hs.c
472
473 hs.hello.cipherSuite = hs.suite.id
David Benjaminece3de92015-03-16 18:02:20 -0400474 if c.config.Bugs.SendCipherSuite != 0 {
475 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
476 }
Adam Langley95c29f32014-06-20 12:00:00 -0700477 // We echo the client's session ID in the ServerHello to let it know
478 // that we're doing a resumption.
479 hs.hello.sessionId = hs.clientHello.sessionId
David Benjaminbed9aae2014-08-07 19:13:38 -0400480 hs.hello.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -0700481
482 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -0400483 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -0400484 hs.writeClientHash(hs.clientHello.marshal())
485 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700486
487 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
488
489 if len(hs.sessionState.certificates) > 0 {
490 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
491 return err
492 }
493 }
494
495 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -0700496 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700497
498 return nil
499}
500
501func (hs *serverHandshakeState) doFullHandshake() error {
502 config := hs.c.config
503 c := hs.c
504
David Benjamin48cae082014-10-27 01:06:24 -0400505 isPSK := hs.suite.flags&suitePSK != 0
506 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700507 hs.hello.ocspStapling = true
508 }
509
David Benjamin61f95272014-11-25 01:55:35 -0500510 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
511 hs.hello.sctList = hs.cert.SignedCertificateTimestampList
512 }
513
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500514 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
Adam Langley95c29f32014-06-20 12:00:00 -0700515 hs.hello.cipherSuite = hs.suite.id
David Benjamin6095de82014-12-27 01:50:38 -0500516 if config.Bugs.SendCipherSuite != 0 {
517 hs.hello.cipherSuite = config.Bugs.SendCipherSuite
518 }
Adam Langley75712922014-10-10 16:23:43 -0700519 c.extendedMasterSecret = hs.hello.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700520
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500521 // Generate a session ID if we're to save the session.
522 if !hs.hello.ticketSupported && config.ServerSessionCache != nil {
523 hs.hello.sessionId = make([]byte, 32)
524 if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
525 c.sendAlert(alertInternalError)
526 return errors.New("tls: short read from Rand: " + err.Error())
527 }
528 }
529
Adam Langley95c29f32014-06-20 12:00:00 -0700530 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400531 hs.writeClientHash(hs.clientHello.marshal())
532 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700533
534 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
535
David Benjamin48cae082014-10-27 01:06:24 -0400536 if !isPSK {
537 certMsg := new(certificateMsg)
David Benjamin8923c0b2015-06-07 11:42:34 -0400538 if !config.Bugs.EmptyCertificateList {
539 certMsg.certificates = hs.cert.Certificate
540 }
David Benjamin48cae082014-10-27 01:06:24 -0400541 if !config.Bugs.UnauthenticatedECDH {
David Benjaminbcb2d912015-02-24 23:45:43 -0500542 certMsgBytes := certMsg.marshal()
543 if config.Bugs.WrongCertificateMessageType {
544 certMsgBytes[0] += 42
545 }
546 hs.writeServerHash(certMsgBytes)
547 c.writeRecord(recordTypeHandshake, certMsgBytes)
David Benjamin48cae082014-10-27 01:06:24 -0400548 }
David Benjamin1c375dd2014-07-12 00:48:23 -0400549 }
Adam Langley95c29f32014-06-20 12:00:00 -0700550
David Benjamindcd979f2015-04-20 18:26:52 -0400551 if hs.hello.ocspStapling && !c.config.Bugs.SkipCertificateStatus {
Adam Langley95c29f32014-06-20 12:00:00 -0700552 certStatus := new(certificateStatusMsg)
553 certStatus.statusType = statusTypeOCSP
554 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -0400555 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700556 c.writeRecord(recordTypeHandshake, certStatus.marshal())
557 }
558
559 keyAgreement := hs.suite.ka(c.vers)
560 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
561 if err != nil {
562 c.sendAlert(alertHandshakeFailure)
563 return err
564 }
David Benjamin9c651c92014-07-12 13:27:45 -0400565 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -0400566 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700567 c.writeRecord(recordTypeHandshake, skx.marshal())
568 }
569
570 if config.ClientAuth >= RequestClientCert {
571 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -0400572 certReq := &certificateRequestMsg{
573 certificateTypes: config.ClientCertificateTypes,
574 }
575 if certReq.certificateTypes == nil {
576 certReq.certificateTypes = []byte{
577 byte(CertTypeRSASign),
578 byte(CertTypeECDSASign),
579 }
Adam Langley95c29f32014-06-20 12:00:00 -0700580 }
581 if c.vers >= VersionTLS12 {
582 certReq.hasSignatureAndHash = true
David Benjamin000800a2014-11-14 01:43:59 -0500583 if !config.Bugs.NoSignatureAndHashes {
584 certReq.signatureAndHashes = config.signatureAndHashesForServer()
585 }
Adam Langley95c29f32014-06-20 12:00:00 -0700586 }
587
588 // An empty list of certificateAuthorities signals to
589 // the client that it may send any certificate in response
590 // to our request. When we know the CAs we trust, then
591 // we can send them down, so that the client can choose
592 // an appropriate certificate to give to us.
593 if config.ClientCAs != nil {
594 certReq.certificateAuthorities = config.ClientCAs.Subjects()
595 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400596 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700597 c.writeRecord(recordTypeHandshake, certReq.marshal())
598 }
599
600 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400601 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700602 c.writeRecord(recordTypeHandshake, helloDone.marshal())
David Benjamina4e6d482015-03-02 19:10:53 -0500603 c.dtlsFlushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700604
605 var pub crypto.PublicKey // public key for client auth, if any
606
David Benjamin83f90402015-01-27 01:09:43 -0500607 if err := c.simulatePacketLoss(nil); err != nil {
608 return err
609 }
Adam Langley95c29f32014-06-20 12:00:00 -0700610 msg, err := c.readHandshake()
611 if err != nil {
612 return err
613 }
614
615 var ok bool
616 // If we requested a client certificate, then the client must send a
617 // certificate message, even if it's empty.
618 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -0400619 var certMsg *certificateMsg
Adam Langley95c29f32014-06-20 12:00:00 -0700620 if certMsg, ok = msg.(*certificateMsg); !ok {
621 c.sendAlert(alertUnexpectedMessage)
622 return unexpectedMessageError(certMsg, msg)
623 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400624 hs.writeClientHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700625
626 if len(certMsg.certificates) == 0 {
627 // The client didn't actually send a certificate
628 switch config.ClientAuth {
629 case RequireAnyClientCert, RequireAndVerifyClientCert:
630 c.sendAlert(alertBadCertificate)
631 return errors.New("tls: client didn't provide a certificate")
632 }
633 }
634
635 pub, err = hs.processCertsFromClient(certMsg.certificates)
636 if err != nil {
637 return err
638 }
639
640 msg, err = c.readHandshake()
641 if err != nil {
642 return err
643 }
644 }
645
646 // Get client key exchange
647 ckx, ok := msg.(*clientKeyExchangeMsg)
648 if !ok {
649 c.sendAlert(alertUnexpectedMessage)
650 return unexpectedMessageError(ckx, msg)
651 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400652 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700653
David Benjamine098ec22014-08-27 23:13:20 -0400654 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
655 if err != nil {
656 c.sendAlert(alertHandshakeFailure)
657 return err
658 }
Adam Langley75712922014-10-10 16:23:43 -0700659 if c.extendedMasterSecret {
660 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
661 } else {
662 if c.config.Bugs.RequireExtendedMasterSecret {
663 return errors.New("tls: extended master secret required but not supported by peer")
664 }
665 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
666 }
David Benjamine098ec22014-08-27 23:13:20 -0400667
Adam Langley95c29f32014-06-20 12:00:00 -0700668 // If we received a client cert in response to our certificate request message,
669 // the client will send us a certificateVerifyMsg immediately after the
670 // clientKeyExchangeMsg. This message is a digest of all preceding
671 // handshake-layer messages that is signed using the private key corresponding
672 // to the client's certificate. This allows us to verify that the client is in
673 // possession of the private key of the certificate.
674 if len(c.peerCertificates) > 0 {
675 msg, err = c.readHandshake()
676 if err != nil {
677 return err
678 }
679 certVerify, ok := msg.(*certificateVerifyMsg)
680 if !ok {
681 c.sendAlert(alertUnexpectedMessage)
682 return unexpectedMessageError(certVerify, msg)
683 }
684
David Benjaminde620d92014-07-18 15:03:41 -0400685 // Determine the signature type.
686 var signatureAndHash signatureAndHash
687 if certVerify.hasSignatureAndHash {
688 signatureAndHash = certVerify.signatureAndHash
David Benjamin000800a2014-11-14 01:43:59 -0500689 if !isSupportedSignatureAndHash(signatureAndHash, config.signatureAndHashesForServer()) {
690 return errors.New("tls: unsupported hash function for client certificate")
691 }
Steven Valdez0d62f262015-09-04 12:41:04 -0400692 c.clientCertSignatureHash = signatureAndHash.hash
David Benjaminde620d92014-07-18 15:03:41 -0400693 } else {
694 // Before TLS 1.2 the signature algorithm was implicit
695 // from the key type, and only one hash per signature
696 // algorithm was possible. Leave the hash as zero.
697 switch pub.(type) {
698 case *ecdsa.PublicKey:
699 signatureAndHash.signature = signatureECDSA
700 case *rsa.PublicKey:
701 signatureAndHash.signature = signatureRSA
702 }
703 }
704
Adam Langley95c29f32014-06-20 12:00:00 -0700705 switch key := pub.(type) {
706 case *ecdsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400707 if signatureAndHash.signature != signatureECDSA {
708 err = errors.New("tls: bad signature type for client's ECDSA certificate")
709 break
710 }
Adam Langley95c29f32014-06-20 12:00:00 -0700711 ecdsaSig := new(ecdsaSignature)
712 if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {
713 break
714 }
715 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
716 err = errors.New("ECDSA signature contained zero or negative values")
717 break
718 }
David Benjaminde620d92014-07-18 15:03:41 -0400719 var digest []byte
David Benjamine098ec22014-08-27 23:13:20 -0400720 digest, _, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400721 if err != nil {
722 break
723 }
Adam Langley95c29f32014-06-20 12:00:00 -0700724 if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {
725 err = errors.New("ECDSA verification failure")
726 break
727 }
728 case *rsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400729 if signatureAndHash.signature != signatureRSA {
730 err = errors.New("tls: bad signature type for client's RSA certificate")
731 break
732 }
733 var digest []byte
734 var hashFunc crypto.Hash
David Benjamine098ec22014-08-27 23:13:20 -0400735 digest, hashFunc, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400736 if err != nil {
737 break
738 }
Adam Langley95c29f32014-06-20 12:00:00 -0700739 err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)
740 }
741 if err != nil {
742 c.sendAlert(alertBadCertificate)
743 return errors.New("could not validate signature of connection nonces: " + err.Error())
744 }
745
David Benjamin83c0bc92014-08-04 01:23:53 -0400746 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700747 }
748
David Benjamine098ec22014-08-27 23:13:20 -0400749 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -0700750
751 return nil
752}
753
754func (hs *serverHandshakeState) establishKeys() error {
755 c := hs.c
756
757 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
758 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
759
760 var clientCipher, serverCipher interface{}
761 var clientHash, serverHash macFunction
762
763 if hs.suite.aead == nil {
764 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
765 clientHash = hs.suite.mac(c.vers, clientMAC)
766 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
767 serverHash = hs.suite.mac(c.vers, serverMAC)
768 } else {
769 clientCipher = hs.suite.aead(clientKey, clientIV)
770 serverCipher = hs.suite.aead(serverKey, serverIV)
771 }
772
773 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
774 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
775
776 return nil
777}
778
Adam Langleyaf0e32c2015-06-03 09:57:23 -0700779func (hs *serverHandshakeState) readFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700780 c := hs.c
781
782 c.readRecord(recordTypeChangeCipherSpec)
783 if err := c.in.error(); err != nil {
784 return err
785 }
786
787 if hs.hello.nextProtoNeg {
788 msg, err := c.readHandshake()
789 if err != nil {
790 return err
791 }
792 nextProto, ok := msg.(*nextProtoMsg)
793 if !ok {
794 c.sendAlert(alertUnexpectedMessage)
795 return unexpectedMessageError(nextProto, msg)
796 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400797 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700798 c.clientProtocol = nextProto.proto
799 }
800
David Benjamind30a9902014-08-24 01:44:23 -0400801 if hs.hello.channelIDRequested {
802 msg, err := c.readHandshake()
803 if err != nil {
804 return err
805 }
806 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
807 if !ok {
808 c.sendAlert(alertUnexpectedMessage)
809 return unexpectedMessageError(encryptedExtensions, msg)
810 }
811 x := new(big.Int).SetBytes(encryptedExtensions.channelID[0:32])
812 y := new(big.Int).SetBytes(encryptedExtensions.channelID[32:64])
813 r := new(big.Int).SetBytes(encryptedExtensions.channelID[64:96])
814 s := new(big.Int).SetBytes(encryptedExtensions.channelID[96:128])
815 if !elliptic.P256().IsOnCurve(x, y) {
816 return errors.New("tls: invalid channel ID public key")
817 }
818 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
819 var resumeHash []byte
820 if isResume {
821 resumeHash = hs.sessionState.handshakeHash
822 }
823 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
824 return errors.New("tls: invalid channel ID signature")
825 }
826 c.channelID = channelID
827
828 hs.writeClientHash(encryptedExtensions.marshal())
829 }
830
Adam Langley95c29f32014-06-20 12:00:00 -0700831 msg, err := c.readHandshake()
832 if err != nil {
833 return err
834 }
835 clientFinished, ok := msg.(*finishedMsg)
836 if !ok {
837 c.sendAlert(alertUnexpectedMessage)
838 return unexpectedMessageError(clientFinished, msg)
839 }
840
841 verify := hs.finishedHash.clientSum(hs.masterSecret)
842 if len(verify) != len(clientFinished.verifyData) ||
843 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
844 c.sendAlert(alertHandshakeFailure)
845 return errors.New("tls: client's Finished message is incorrect")
846 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700847 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -0700848 copy(out, clientFinished.verifyData)
Adam Langley95c29f32014-06-20 12:00:00 -0700849
David Benjamin83c0bc92014-08-04 01:23:53 -0400850 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700851 return nil
852}
853
854func (hs *serverHandshakeState) sendSessionTicket() error {
Adam Langley95c29f32014-06-20 12:00:00 -0700855 c := hs.c
Adam Langley95c29f32014-06-20 12:00:00 -0700856 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -0400857 vers: c.vers,
858 cipherSuite: hs.suite.id,
859 masterSecret: hs.masterSecret,
860 certificates: hs.certsFromClient,
861 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -0700862 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500863
864 if !hs.hello.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
865 if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
866 c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
867 }
868 return nil
869 }
870
871 m := new(newSessionTicketMsg)
872
David Benjamindd6fed92015-10-23 17:41:12 -0400873 if !c.config.Bugs.SendEmptySessionTicket {
874 var err error
875 m.ticket, err = c.encryptTicket(&state)
876 if err != nil {
877 return err
878 }
Adam Langley95c29f32014-06-20 12:00:00 -0700879 }
Adam Langley95c29f32014-06-20 12:00:00 -0700880
David Benjamin83c0bc92014-08-04 01:23:53 -0400881 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700882 c.writeRecord(recordTypeHandshake, m.marshal())
883
884 return nil
885}
886
Adam Langleyaf0e32c2015-06-03 09:57:23 -0700887func (hs *serverHandshakeState) sendFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700888 c := hs.c
889
David Benjamin86271ee2014-07-21 16:14:03 -0400890 finished := new(finishedMsg)
891 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
Adam Langleyaf0e32c2015-06-03 09:57:23 -0700892 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -0400893 if c.config.Bugs.BadFinished {
894 finished.verifyData[0]++
895 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700896 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -0500897 hs.finishedBytes = finished.marshal()
898 hs.writeServerHash(hs.finishedBytes)
899 postCCSBytes := hs.finishedBytes
David Benjamin86271ee2014-07-21 16:14:03 -0400900
901 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
902 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
903 postCCSBytes = postCCSBytes[5:]
904 }
David Benjamina4e6d482015-03-02 19:10:53 -0500905 c.dtlsFlushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -0400906
David Benjamina0e52232014-07-19 17:39:58 -0400907 if !c.config.Bugs.SkipChangeCipherSpec {
908 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
909 }
Adam Langley95c29f32014-06-20 12:00:00 -0700910
David Benjamin4189bd92015-01-25 23:52:39 -0500911 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
912 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
913 }
David Benjamindc3da932015-03-12 15:09:02 -0400914 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
915 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
916 return errors.New("tls: simulating post-CCS alert")
917 }
David Benjamin4189bd92015-01-25 23:52:39 -0500918
David Benjaminb80168e2015-02-08 18:30:14 -0500919 if !c.config.Bugs.SkipFinished {
920 c.writeRecord(recordTypeHandshake, postCCSBytes)
David Benjamina4e6d482015-03-02 19:10:53 -0500921 c.dtlsFlushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -0500922 }
Adam Langley95c29f32014-06-20 12:00:00 -0700923
David Benjaminc565ebb2015-04-03 04:06:36 -0400924 c.cipherSuite = hs.suite
Adam Langley95c29f32014-06-20 12:00:00 -0700925
926 return nil
927}
928
929// processCertsFromClient takes a chain of client certificates either from a
930// Certificates message or from a sessionState and verifies them. It returns
931// the public key of the leaf certificate.
932func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
933 c := hs.c
934
935 hs.certsFromClient = certificates
936 certs := make([]*x509.Certificate, len(certificates))
937 var err error
938 for i, asn1Data := range certificates {
939 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
940 c.sendAlert(alertBadCertificate)
941 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
942 }
943 }
944
945 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
946 opts := x509.VerifyOptions{
947 Roots: c.config.ClientCAs,
948 CurrentTime: c.config.time(),
949 Intermediates: x509.NewCertPool(),
950 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
951 }
952
953 for _, cert := range certs[1:] {
954 opts.Intermediates.AddCert(cert)
955 }
956
957 chains, err := certs[0].Verify(opts)
958 if err != nil {
959 c.sendAlert(alertBadCertificate)
960 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
961 }
962
963 ok := false
964 for _, ku := range certs[0].ExtKeyUsage {
965 if ku == x509.ExtKeyUsageClientAuth {
966 ok = true
967 break
968 }
969 }
970 if !ok {
971 c.sendAlert(alertHandshakeFailure)
972 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
973 }
974
975 c.verifiedChains = chains
976 }
977
978 if len(certs) > 0 {
979 var pub crypto.PublicKey
980 switch key := certs[0].PublicKey.(type) {
981 case *ecdsa.PublicKey, *rsa.PublicKey:
982 pub = key
983 default:
984 c.sendAlert(alertUnsupportedCertificate)
985 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
986 }
987 c.peerCertificates = certs
988 return pub, nil
989 }
990
991 return nil, nil
992}
993
David Benjamin83c0bc92014-08-04 01:23:53 -0400994func (hs *serverHandshakeState) writeServerHash(msg []byte) {
995 // writeServerHash is called before writeRecord.
996 hs.writeHash(msg, hs.c.sendHandshakeSeq)
997}
998
999func (hs *serverHandshakeState) writeClientHash(msg []byte) {
1000 // writeClientHash is called after readHandshake.
1001 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1002}
1003
1004func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
1005 if hs.c.isDTLS {
1006 // This is somewhat hacky. DTLS hashes a slightly different format.
1007 // First, the TLS header.
1008 hs.finishedHash.Write(msg[:4])
1009 // Then the sequence number and reassembled fragment offset (always 0).
1010 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1011 // Then the reassembled fragment (always equal to the message length).
1012 hs.finishedHash.Write(msg[1:4])
1013 // And then the message body.
1014 hs.finishedHash.Write(msg[4:])
1015 } else {
1016 hs.finishedHash.Write(msg)
1017 }
1018}
1019
Adam Langley95c29f32014-06-20 12:00:00 -07001020// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
1021// is acceptable to use.
1022func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
1023 for _, supported := range supportedCipherSuites {
1024 if id == supported {
1025 var candidate *cipherSuite
1026
1027 for _, s := range cipherSuites {
1028 if s.id == id {
1029 candidate = s
1030 break
1031 }
1032 }
1033 if candidate == nil {
1034 continue
1035 }
1036 // Don't select a ciphersuite which we can't
1037 // support for this client.
1038 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
1039 continue
1040 }
1041 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
1042 continue
1043 }
David Benjamin39ebf532014-08-31 02:23:49 -04001044 if !c.config.Bugs.SkipCipherVersionCheck && version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
Adam Langley95c29f32014-06-20 12:00:00 -07001045 continue
1046 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001047 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
1048 continue
1049 }
Adam Langley95c29f32014-06-20 12:00:00 -07001050 return candidate
1051 }
1052 }
1053
1054 return nil
1055}