blob: 300ab50379f0815d9a588a3ac0b5c50b6707e52a [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"
Adam Langley95c29f32014-06-20 12:00:00 -070015 "errors"
16 "fmt"
17 "io"
David Benjamind30a9902014-08-24 01:44:23 -040018 "math/big"
Adam Langley95c29f32014-06-20 12:00:00 -070019)
20
21// serverHandshakeState contains details of a server handshake in progress.
22// It's discarded once the handshake has completed.
23type serverHandshakeState struct {
24 c *Conn
25 clientHello *clientHelloMsg
26 hello *serverHelloMsg
27 suite *cipherSuite
28 ellipticOk bool
29 ecdsaOk bool
30 sessionState *sessionState
31 finishedHash finishedHash
32 masterSecret []byte
33 certsFromClient [][]byte
34 cert *Certificate
David Benjamin83f90402015-01-27 01:09:43 -050035 finishedBytes []byte
Adam Langley95c29f32014-06-20 12:00:00 -070036}
37
38// serverHandshake performs a TLS handshake as a server.
39func (c *Conn) serverHandshake() error {
40 config := c.config
41
42 // If this is the first server handshake, we generate a random key to
43 // encrypt the tickets with.
44 config.serverInitOnce.Do(config.serverInit)
45
David Benjamin83c0bc92014-08-04 01:23:53 -040046 c.sendHandshakeSeq = 0
47 c.recvHandshakeSeq = 0
48
Adam Langley95c29f32014-06-20 12:00:00 -070049 hs := serverHandshakeState{
50 c: c,
51 }
David Benjaminf25dda92016-07-04 10:05:26 -070052 if err := hs.readClientHello(); err != nil {
53 return err
54 }
Adam Langley95c29f32014-06-20 12:00:00 -070055
David Benjamin8d315d72016-07-18 01:03:18 +020056 if c.vers >= VersionTLS13 {
Nick Harper728eed82016-07-07 17:36:52 -070057 if err := hs.doTLS13Handshake(); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -070058 return err
59 }
Nick Harper728eed82016-07-07 17:36:52 -070060 } else {
61 isResume, err := hs.processClientHello()
62 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -070063 return err
64 }
Nick Harper728eed82016-07-07 17:36:52 -070065
66 // For an overview of TLS handshaking, see https://tools.ietf.org/html/rfc5246#section-7.3
67 if isResume {
68 // The client has included a session ticket and so we do an abbreviated handshake.
69 if err := hs.doResumeHandshake(); err != nil {
70 return err
71 }
72 if err := hs.establishKeys(); err != nil {
73 return err
74 }
75 if c.config.Bugs.RenewTicketOnResume {
76 if err := hs.sendSessionTicket(); err != nil {
77 return err
78 }
79 }
80 if err := hs.sendFinished(c.firstFinished[:]); err != nil {
81 return err
82 }
83 // Most retransmits are triggered by a timeout, but the final
84 // leg of the handshake is retransmited upon re-receiving a
85 // Finished.
86 if err := c.simulatePacketLoss(func() {
87 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
88 c.flushHandshake()
89 }); err != nil {
90 return err
91 }
92 if err := hs.readFinished(nil, isResume); err != nil {
93 return err
94 }
95 c.didResume = true
96 } else {
97 // The client didn't include a session ticket, or it wasn't
98 // valid so we do a full handshake.
99 if err := hs.doFullHandshake(); err != nil {
100 return err
101 }
102 if err := hs.establishKeys(); err != nil {
103 return err
104 }
105 if err := hs.readFinished(c.firstFinished[:], isResume); err != nil {
106 return err
107 }
108 if c.config.Bugs.AlertBeforeFalseStartTest != 0 {
109 c.sendAlert(c.config.Bugs.AlertBeforeFalseStartTest)
110 }
111 if c.config.Bugs.ExpectFalseStart {
112 if err := c.readRecord(recordTypeApplicationData); err != nil {
113 return fmt.Errorf("tls: peer did not false start: %s", err)
114 }
115 }
David Benjaminbed9aae2014-08-07 19:13:38 -0400116 if err := hs.sendSessionTicket(); err != nil {
117 return err
118 }
Nick Harper728eed82016-07-07 17:36:52 -0700119 if err := hs.sendFinished(nil); err != nil {
120 return err
David Benjamine58c4f52014-08-24 03:47:07 -0400121 }
122 }
David Benjamin97a0a082016-07-13 17:57:35 -0400123
124 c.exporterSecret = hs.masterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700125 }
126 c.handshakeComplete = true
David Benjaminc565ebb2015-04-03 04:06:36 -0400127 copy(c.clientRandom[:], hs.clientHello.random)
128 copy(c.serverRandom[:], hs.hello.random)
Adam Langley95c29f32014-06-20 12:00:00 -0700129
130 return nil
131}
132
David Benjaminf25dda92016-07-04 10:05:26 -0700133// readClientHello reads a ClientHello message from the client and determines
134// the protocol version.
135func (hs *serverHandshakeState) readClientHello() error {
Adam Langley95c29f32014-06-20 12:00:00 -0700136 config := hs.c.config
137 c := hs.c
138
David Benjamin83f90402015-01-27 01:09:43 -0500139 if err := c.simulatePacketLoss(nil); err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700140 return err
David Benjamin83f90402015-01-27 01:09:43 -0500141 }
Adam Langley95c29f32014-06-20 12:00:00 -0700142 msg, err := c.readHandshake()
143 if err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700144 return err
Adam Langley95c29f32014-06-20 12:00:00 -0700145 }
146 var ok bool
147 hs.clientHello, ok = msg.(*clientHelloMsg)
148 if !ok {
149 c.sendAlert(alertUnexpectedMessage)
David Benjaminf25dda92016-07-04 10:05:26 -0700150 return unexpectedMessageError(hs.clientHello, msg)
Adam Langley95c29f32014-06-20 12:00:00 -0700151 }
Adam Langley33ad2b52015-07-20 17:43:53 -0700152 if size := config.Bugs.RequireClientHelloSize; size != 0 && len(hs.clientHello.raw) != size {
David Benjaminf25dda92016-07-04 10:05:26 -0700153 return fmt.Errorf("tls: ClientHello record size is %d, but expected %d", len(hs.clientHello.raw), size)
Feng Lu41aa3252014-11-21 22:47:56 -0800154 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400155
156 if c.isDTLS && !config.Bugs.SkipHelloVerifyRequest {
David Benjamin8bc38f52014-08-16 12:07:27 -0400157 // Per RFC 6347, the version field in HelloVerifyRequest SHOULD
158 // be always DTLS 1.0
David Benjamin83c0bc92014-08-04 01:23:53 -0400159 helloVerifyRequest := &helloVerifyRequestMsg{
David Benjamin8bc38f52014-08-16 12:07:27 -0400160 vers: VersionTLS10,
David Benjamin83c0bc92014-08-04 01:23:53 -0400161 cookie: make([]byte, 32),
162 }
163 if _, err := io.ReadFull(c.config.rand(), helloVerifyRequest.cookie); err != nil {
164 c.sendAlert(alertInternalError)
David Benjaminf25dda92016-07-04 10:05:26 -0700165 return errors.New("dtls: short read from Rand: " + err.Error())
David Benjamin83c0bc92014-08-04 01:23:53 -0400166 }
167 c.writeRecord(recordTypeHandshake, helloVerifyRequest.marshal())
David Benjamin582ba042016-07-07 12:33:25 -0700168 c.flushHandshake()
David Benjamin83c0bc92014-08-04 01:23:53 -0400169
David Benjamin83f90402015-01-27 01:09:43 -0500170 if err := c.simulatePacketLoss(nil); err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700171 return err
David Benjamin83f90402015-01-27 01:09:43 -0500172 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400173 msg, err := c.readHandshake()
174 if err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700175 return err
David Benjamin83c0bc92014-08-04 01:23:53 -0400176 }
177 newClientHello, ok := msg.(*clientHelloMsg)
178 if !ok {
179 c.sendAlert(alertUnexpectedMessage)
David Benjaminf25dda92016-07-04 10:05:26 -0700180 return unexpectedMessageError(hs.clientHello, msg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400181 }
182 if !bytes.Equal(newClientHello.cookie, helloVerifyRequest.cookie) {
David Benjaminf25dda92016-07-04 10:05:26 -0700183 return errors.New("dtls: invalid cookie")
David Benjamin83c0bc92014-08-04 01:23:53 -0400184 }
David Benjaminf2fedef2014-08-16 01:37:34 -0400185
186 // Apart from the cookie, the two ClientHellos must
187 // match. Note that clientHello.equal compares the
188 // serialization, so we make a copy.
189 oldClientHelloCopy := *hs.clientHello
190 oldClientHelloCopy.raw = nil
191 oldClientHelloCopy.cookie = nil
192 newClientHelloCopy := *newClientHello
193 newClientHelloCopy.raw = nil
194 newClientHelloCopy.cookie = nil
195 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
David Benjaminf25dda92016-07-04 10:05:26 -0700196 return errors.New("dtls: retransmitted ClientHello does not match")
David Benjamin83c0bc92014-08-04 01:23:53 -0400197 }
198 hs.clientHello = newClientHello
199 }
200
David Benjaminc44b1df2014-11-23 12:11:01 -0500201 if config.Bugs.RequireSameRenegoClientVersion && c.clientVersion != 0 {
202 if c.clientVersion != hs.clientHello.vers {
David Benjaminf25dda92016-07-04 10:05:26 -0700203 return fmt.Errorf("tls: client offered different version on renego")
David Benjaminc44b1df2014-11-23 12:11:01 -0500204 }
205 }
206 c.clientVersion = hs.clientHello.vers
207
David Benjamin6ae7f072015-01-26 10:22:13 -0500208 // Reject < 1.2 ClientHellos with signature_algorithms.
Nick Harper60edffd2016-06-21 15:19:24 -0700209 if c.clientVersion < VersionTLS12 && len(hs.clientHello.signatureAlgorithms) > 0 {
David Benjaminf25dda92016-07-04 10:05:26 -0700210 return fmt.Errorf("tls: client included signature_algorithms before TLS 1.2")
David Benjamin72dc7832015-03-16 17:49:43 -0400211 }
David Benjamin6ae7f072015-01-26 10:22:13 -0500212
David Benjaminf93995b2015-11-05 18:23:20 -0500213 // Check the client cipher list is consistent with the version.
214 if hs.clientHello.vers < VersionTLS12 {
215 for _, id := range hs.clientHello.cipherSuites {
216 if isTLS12Cipher(id) {
David Benjaminf25dda92016-07-04 10:05:26 -0700217 return fmt.Errorf("tls: client offered TLS 1.2 cipher before TLS 1.2")
David Benjaminf93995b2015-11-05 18:23:20 -0500218 }
219 }
220 }
221
David Benjamin1f61f0d2016-07-10 12:20:35 -0400222 if config.Bugs.NegotiateVersion != 0 {
223 c.vers = config.Bugs.NegotiateVersion
224 } else {
225 c.vers, ok = config.mutualVersion(hs.clientHello.vers, c.isDTLS)
226 if !ok {
227 c.sendAlert(alertProtocolVersion)
228 return fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
229 }
David Benjamin8bc38f52014-08-16 12:07:27 -0400230 }
Adam Langley95c29f32014-06-20 12:00:00 -0700231 c.haveVers = true
232
David Benjaminf25dda92016-07-04 10:05:26 -0700233 var scsvFound bool
234 for _, cipherSuite := range hs.clientHello.cipherSuites {
235 if cipherSuite == fallbackSCSV {
236 scsvFound = true
237 break
238 }
239 }
240
241 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
242 return errors.New("tls: no fallback SCSV found when expected")
243 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
244 return errors.New("tls: fallback SCSV found when not expected")
245 }
246
247 if config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
David Benjamin7a41d372016-07-09 11:21:54 -0700248 hs.clientHello.signatureAlgorithms = config.signSignatureAlgorithms()
David Benjaminf25dda92016-07-04 10:05:26 -0700249 }
250 if config.Bugs.IgnorePeerCurvePreferences {
251 hs.clientHello.supportedCurves = config.curvePreferences()
252 }
253 if config.Bugs.IgnorePeerCipherPreferences {
254 hs.clientHello.cipherSuites = config.cipherSuites()
255 }
256
257 return nil
258}
259
Nick Harper728eed82016-07-07 17:36:52 -0700260func (hs *serverHandshakeState) doTLS13Handshake() error {
261 c := hs.c
262 config := c.config
263
264 hs.hello = &serverHelloMsg{
265 isDTLS: c.isDTLS,
266 vers: c.vers,
267 }
268
269 hs.hello.random = make([]byte, 32)
270 if _, err := io.ReadFull(config.rand(), hs.hello.random); err != nil {
271 c.sendAlert(alertInternalError)
272 return err
273 }
274
275 // TLS 1.3 forbids clients from advertising any non-null compression.
276 if len(hs.clientHello.compressionMethods) != 1 || hs.clientHello.compressionMethods[0] != compressionNone {
277 return errors.New("tls: client sent compression method other than null for TLS 1.3")
278 }
279
280 // Prepare an EncryptedExtensions message, but do not send it yet.
281 encryptedExtensions := new(encryptedExtensionsMsg)
Steven Valdez143e8b32016-07-11 13:19:03 -0400282 encryptedExtensions.empty = config.Bugs.EmptyEncryptedExtensions
Nick Harper728eed82016-07-07 17:36:52 -0700283 if err := hs.processClientExtensions(&encryptedExtensions.extensions); err != nil {
284 return err
285 }
286
287 supportedCurve := false
288 var selectedCurve CurveID
289 preferredCurves := config.curvePreferences()
290Curves:
291 for _, curve := range hs.clientHello.supportedCurves {
292 for _, supported := range preferredCurves {
293 if supported == curve {
294 supportedCurve = true
295 selectedCurve = curve
296 break Curves
297 }
298 }
299 }
300
301 _, ecdsaOk := hs.cert.PrivateKey.(*ecdsa.PrivateKey)
302
303 // TODO(davidben): Implement PSK support.
304 pskOk := false
305
306 // Select the cipher suite.
307 var preferenceList, supportedList []uint16
308 if config.PreferServerCipherSuites {
309 preferenceList = config.cipherSuites()
310 supportedList = hs.clientHello.cipherSuites
311 } else {
312 preferenceList = hs.clientHello.cipherSuites
313 supportedList = config.cipherSuites()
314 }
315
316 for _, id := range preferenceList {
317 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, supportedCurve, ecdsaOk, pskOk); hs.suite != nil {
318 break
319 }
320 }
321
322 if hs.suite == nil {
323 c.sendAlert(alertHandshakeFailure)
324 return errors.New("tls: no cipher suite supported by both client and server")
325 }
326
327 hs.hello.cipherSuite = hs.suite.id
Steven Valdez0ee2e112016-07-15 06:51:15 -0400328 if c.config.Bugs.SendCipherSuite != 0 {
329 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
330 }
331
Nick Harper728eed82016-07-07 17:36:52 -0700332 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
333 hs.finishedHash.discardHandshakeBuffer()
334 hs.writeClientHash(hs.clientHello.marshal())
335
336 // Resolve PSK and compute the early secret.
David Benjaminc87ebde2016-07-13 17:26:02 -0400337 // TODO(davidben): Implement PSK in TLS 1.3.
338 psk := hs.finishedHash.zeroSecret()
339 hs.finishedHash.setResumptionContext(hs.finishedHash.zeroSecret())
Nick Harper728eed82016-07-07 17:36:52 -0700340
341 earlySecret := hs.finishedHash.extractKey(hs.finishedHash.zeroSecret(), psk)
342
343 // Resolve ECDHE and compute the handshake secret.
344 var ecdheSecret []byte
Steven Valdez143e8b32016-07-11 13:19:03 -0400345 if hs.suite.flags&suiteECDHE != 0 && !config.Bugs.MissingKeyShare {
Nick Harper728eed82016-07-07 17:36:52 -0700346 // Look for the key share corresponding to our selected curve.
347 var selectedKeyShare *keyShareEntry
348 for i := range hs.clientHello.keyShares {
349 if hs.clientHello.keyShares[i].group == selectedCurve {
350 selectedKeyShare = &hs.clientHello.keyShares[i]
351 break
352 }
353 }
354
355 if selectedKeyShare == nil {
Nick Harperdcfbc672016-07-16 17:47:31 +0200356 // Send HelloRetryRequest.
357 helloRetryRequestMsg := helloRetryRequestMsg{
358 vers: c.vers,
359 cipherSuite: hs.hello.cipherSuite,
360 selectedGroup: selectedCurve,
361 }
362 hs.writeServerHash(helloRetryRequestMsg.marshal())
363 c.writeRecord(recordTypeHandshake, helloRetryRequestMsg.marshal())
364
365 // Read new ClientHello.
366 newMsg, err := c.readHandshake()
367 if err != nil {
368 return err
369 }
370 newClientHello, ok := newMsg.(*clientHelloMsg)
371 if !ok {
372 c.sendAlert(alertUnexpectedMessage)
373 return unexpectedMessageError(newClientHello, newMsg)
374 }
375 hs.writeClientHash(newClientHello.marshal())
376
377 // Check that the new ClientHello matches the old ClientHello, except for
378 // the addition of the new KeyShareEntry at the end of the list, and
379 // removing the EarlyDataIndication extension (if present).
380 newKeyShares := newClientHello.keyShares
381 if len(newKeyShares) == 0 || newKeyShares[len(newKeyShares)-1].group != selectedCurve {
382 return errors.New("tls: KeyShare from HelloRetryRequest not present in new ClientHello")
383 }
384 oldClientHelloCopy := *hs.clientHello
385 oldClientHelloCopy.raw = nil
386 oldClientHelloCopy.hasEarlyData = false
387 oldClientHelloCopy.earlyDataContext = nil
388 newClientHelloCopy := *newClientHello
389 newClientHelloCopy.raw = nil
390 newClientHelloCopy.keyShares = newKeyShares[:len(newKeyShares)-1]
391 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
392 return errors.New("tls: new ClientHello does not match")
393 }
394
395 selectedKeyShare = &newKeyShares[len(newKeyShares)-1]
Nick Harper728eed82016-07-07 17:36:52 -0700396 }
397
398 // Once a curve has been selected and a key share identified,
399 // the server needs to generate a public value and send it in
400 // the ServerHello.
401 curve, ok := curveForCurveID(selectedKeyShare.group)
402 if !ok {
403 panic("tls: server failed to look up curve ID")
404 }
405 var publicKey []byte
406 var err error
407 publicKey, ecdheSecret, err = curve.accept(config.rand(), selectedKeyShare.keyExchange)
408 if err != nil {
409 c.sendAlert(alertHandshakeFailure)
410 return err
411 }
412 hs.hello.hasKeyShare = true
Steven Valdez0ee2e112016-07-15 06:51:15 -0400413
414 curveID := selectedKeyShare.group
415 if c.config.Bugs.SendCurve != 0 {
416 curveID = config.Bugs.SendCurve
417 }
418 if c.config.Bugs.InvalidECDHPoint {
419 publicKey[0] ^= 0xff
420 }
421
Nick Harper728eed82016-07-07 17:36:52 -0700422 hs.hello.keyShare = keyShareEntry{
Steven Valdez0ee2e112016-07-15 06:51:15 -0400423 group: curveID,
Nick Harper728eed82016-07-07 17:36:52 -0700424 keyExchange: publicKey,
425 }
Steven Valdez143e8b32016-07-11 13:19:03 -0400426
427 if config.Bugs.EncryptedExtensionsWithKeyShare {
428 encryptedExtensions.extensions.hasKeyShare = true
429 encryptedExtensions.extensions.keyShare = keyShareEntry{
430 group: curveID,
431 keyExchange: publicKey,
432 }
433 }
Nick Harper728eed82016-07-07 17:36:52 -0700434 } else {
435 ecdheSecret = hs.finishedHash.zeroSecret()
436 }
437
438 // Send unencrypted ServerHello.
439 hs.writeServerHash(hs.hello.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400440 if config.Bugs.PartialEncryptedExtensionsWithServerHello {
441 helloBytes := hs.hello.marshal()
442 toWrite := make([]byte, 0, len(helloBytes)+1)
443 toWrite = append(toWrite, helloBytes...)
444 toWrite = append(toWrite, typeEncryptedExtensions)
445 c.writeRecord(recordTypeHandshake, toWrite)
446 } else {
447 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
448 }
Nick Harper728eed82016-07-07 17:36:52 -0700449 c.flushHandshake()
450
451 // Compute the handshake secret.
452 handshakeSecret := hs.finishedHash.extractKey(earlySecret, ecdheSecret)
453
454 // Switch to handshake traffic keys.
455 handshakeTrafficSecret := hs.finishedHash.deriveSecret(handshakeSecret, handshakeTrafficLabel)
456 c.out.updateKeys(deriveTrafficAEAD(c.vers, hs.suite, handshakeTrafficSecret, handshakePhase, serverWrite), c.vers)
457 c.in.updateKeys(deriveTrafficAEAD(c.vers, hs.suite, handshakeTrafficSecret, handshakePhase, clientWrite), c.vers)
458
David Benjamin615119a2016-07-06 19:22:55 -0700459 if hs.suite.flags&suitePSK != 0 {
David Benjaminc87ebde2016-07-13 17:26:02 -0400460 return errors.New("tls: PSK ciphers not implemented for TLS 1.3")
461 } else {
David Benjamin615119a2016-07-06 19:22:55 -0700462 if hs.clientHello.ocspStapling {
463 encryptedExtensions.extensions.ocspResponse = hs.cert.OCSPStaple
464 }
465 if hs.clientHello.sctListSupported {
466 encryptedExtensions.extensions.sctList = hs.cert.SignedCertificateTimestampList
467 }
468 }
469
Nick Harper728eed82016-07-07 17:36:52 -0700470 // Send EncryptedExtensions.
471 hs.writeServerHash(encryptedExtensions.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400472 if config.Bugs.PartialEncryptedExtensionsWithServerHello {
473 // The first byte has already been sent.
474 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()[1:])
475 } else {
476 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal())
477 }
Nick Harper728eed82016-07-07 17:36:52 -0700478
479 if hs.suite.flags&suitePSK == 0 {
480 if config.ClientAuth >= RequestClientCert {
David Benjamin8d343b42016-07-09 14:26:01 -0700481 // Request a client certificate
482 certReq := &certificateRequestMsg{
483 hasSignatureAlgorithm: true,
484 hasRequestContext: true,
485 }
486 if !config.Bugs.NoSignatureAlgorithms {
David Benjaminf74ec792016-07-13 21:18:49 -0400487 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin8d343b42016-07-09 14:26:01 -0700488 }
489
490 // An empty list of certificateAuthorities signals to
491 // the client that it may send any certificate in response
492 // to our request. When we know the CAs we trust, then
493 // we can send them down, so that the client can choose
494 // an appropriate certificate to give to us.
495 if config.ClientCAs != nil {
496 certReq.certificateAuthorities = config.ClientCAs.Subjects()
497 }
498 hs.writeServerHash(certReq.marshal())
499 c.writeRecord(recordTypeHandshake, certReq.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700500 }
501
502 certMsg := &certificateMsg{
503 hasRequestContext: true,
504 }
505 if !config.Bugs.EmptyCertificateList {
506 certMsg.certificates = hs.cert.Certificate
507 }
David Benjamin1edae6b2016-07-13 16:58:23 -0400508 certMsgBytes := certMsg.marshal()
David Benjamin1edae6b2016-07-13 16:58:23 -0400509 hs.writeServerHash(certMsgBytes)
510 c.writeRecord(recordTypeHandshake, certMsgBytes)
Nick Harper728eed82016-07-07 17:36:52 -0700511
512 certVerify := &certificateVerifyMsg{
513 hasSignatureAlgorithm: true,
514 }
515
516 // Determine the hash to sign.
517 privKey := hs.cert.PrivateKey
518
519 var err error
520 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, config, hs.clientHello.signatureAlgorithms)
521 if err != nil {
522 c.sendAlert(alertInternalError)
523 return err
524 }
525
526 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
527 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
528 if err != nil {
529 c.sendAlert(alertInternalError)
530 return err
531 }
532
Steven Valdez0ee2e112016-07-15 06:51:15 -0400533 if config.Bugs.SendSignatureAlgorithm != 0 {
534 certVerify.signatureAlgorithm = config.Bugs.SendSignatureAlgorithm
535 }
536
Nick Harper728eed82016-07-07 17:36:52 -0700537 hs.writeServerHash(certVerify.marshal())
538 c.writeRecord(recordTypeHandshake, certVerify.marshal())
539 }
540
541 finished := new(finishedMsg)
542 finished.verifyData = hs.finishedHash.serverSum(handshakeTrafficSecret)
543 if config.Bugs.BadFinished {
544 finished.verifyData[0]++
545 }
546 hs.writeServerHash(finished.marshal())
547 c.writeRecord(recordTypeHandshake, finished.marshal())
548 c.flushHandshake()
549
550 // The various secrets do not incorporate the client's final leg, so
551 // derive them now before updating the handshake context.
552 masterSecret := hs.finishedHash.extractKey(handshakeSecret, hs.finishedHash.zeroSecret())
553 trafficSecret := hs.finishedHash.deriveSecret(masterSecret, applicationTrafficLabel)
554
David Benjamin2aad4062016-07-14 23:15:40 -0400555 // Switch to application data keys on write. In particular, any alerts
556 // from the client certificate are sent over these keys.
557 c.out.updateKeys(deriveTrafficAEAD(c.vers, hs.suite, trafficSecret, applicationPhase, serverWrite), c.vers)
558
Nick Harper728eed82016-07-07 17:36:52 -0700559 // If we requested a client certificate, then the client must send a
560 // certificate message, even if it's empty.
561 if config.ClientAuth >= RequestClientCert {
David Benjamin8d343b42016-07-09 14:26:01 -0700562 msg, err := c.readHandshake()
563 if err != nil {
564 return err
565 }
566
567 certMsg, ok := msg.(*certificateMsg)
568 if !ok {
569 c.sendAlert(alertUnexpectedMessage)
570 return unexpectedMessageError(certMsg, msg)
571 }
572 hs.writeClientHash(certMsg.marshal())
573
574 if len(certMsg.certificates) == 0 {
575 // The client didn't actually send a certificate
576 switch config.ClientAuth {
577 case RequireAnyClientCert, RequireAndVerifyClientCert:
578 c.sendAlert(alertBadCertificate)
579 return errors.New("tls: client didn't provide a certificate")
580 }
581 }
582
583 pub, err := hs.processCertsFromClient(certMsg.certificates)
584 if err != nil {
585 return err
586 }
587
588 if len(c.peerCertificates) > 0 {
589 msg, err = c.readHandshake()
590 if err != nil {
591 return err
592 }
593
594 certVerify, ok := msg.(*certificateVerifyMsg)
595 if !ok {
596 c.sendAlert(alertUnexpectedMessage)
597 return unexpectedMessageError(certVerify, msg)
598 }
599
David Benjaminf74ec792016-07-13 21:18:49 -0400600 c.peerSignatureAlgorithm = certVerify.signatureAlgorithm
David Benjamin8d343b42016-07-09 14:26:01 -0700601 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
602 if err := verifyMessage(c.vers, pub, config, certVerify.signatureAlgorithm, input, certVerify.signature); err != nil {
603 c.sendAlert(alertBadCertificate)
604 return err
605 }
606 hs.writeClientHash(certVerify.marshal())
607 }
Nick Harper728eed82016-07-07 17:36:52 -0700608 }
609
610 // Read the client Finished message.
611 msg, err := c.readHandshake()
612 if err != nil {
613 return err
614 }
615 clientFinished, ok := msg.(*finishedMsg)
616 if !ok {
617 c.sendAlert(alertUnexpectedMessage)
618 return unexpectedMessageError(clientFinished, msg)
619 }
620
621 verify := hs.finishedHash.clientSum(handshakeTrafficSecret)
622 if len(verify) != len(clientFinished.verifyData) ||
623 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
624 c.sendAlert(alertHandshakeFailure)
625 return errors.New("tls: client's Finished message was incorrect")
626 }
David Benjamin97a0a082016-07-13 17:57:35 -0400627 hs.writeClientHash(clientFinished.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700628
David Benjamin2aad4062016-07-14 23:15:40 -0400629 // Switch to application data keys on read.
Nick Harper728eed82016-07-07 17:36:52 -0700630 c.in.updateKeys(deriveTrafficAEAD(c.vers, hs.suite, trafficSecret, applicationPhase, clientWrite), c.vers)
631
Nick Harper728eed82016-07-07 17:36:52 -0700632 // TODO(davidben): Derive and save the resumption master secret for receiving tickets.
633 // TODO(davidben): Save the traffic secret for KeyUpdate.
634 c.cipherSuite = hs.suite
David Benjamin97a0a082016-07-13 17:57:35 -0400635 c.exporterSecret = hs.finishedHash.deriveSecret(masterSecret, exporterLabel)
Nick Harper728eed82016-07-07 17:36:52 -0700636 return nil
637}
638
David Benjaminf25dda92016-07-04 10:05:26 -0700639// processClientHello processes the ClientHello message from the client and
640// decides whether we will perform session resumption.
641func (hs *serverHandshakeState) processClientHello() (isResume bool, err error) {
642 config := hs.c.config
643 c := hs.c
644
645 hs.hello = &serverHelloMsg{
646 isDTLS: c.isDTLS,
647 vers: c.vers,
648 compressionMethod: compressionNone,
649 }
650
651 hs.hello.random = make([]byte, 32)
652 _, err = io.ReadFull(config.rand(), hs.hello.random)
653 if err != nil {
654 c.sendAlert(alertInternalError)
655 return false, err
656 }
David Benjamin1f61f0d2016-07-10 12:20:35 -0400657 // Signal downgrades in the server random, per draft-ietf-tls-tls13-14,
658 // section 6.3.1.2.
Nick Harper85f20c22016-07-04 10:11:59 -0700659 if c.vers <= VersionTLS12 && config.maxVersion(c.isDTLS) >= VersionTLS13 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400660 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS13)
Nick Harper85f20c22016-07-04 10:11:59 -0700661 }
662 if c.vers <= VersionTLS11 && config.maxVersion(c.isDTLS) == VersionTLS12 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400663 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS12)
Nick Harper85f20c22016-07-04 10:11:59 -0700664 }
David Benjaminf25dda92016-07-04 10:05:26 -0700665
666 foundCompression := false
667 // We only support null compression, so check that the client offered it.
668 for _, compression := range hs.clientHello.compressionMethods {
669 if compression == compressionNone {
670 foundCompression = true
671 break
672 }
673 }
674
675 if !foundCompression {
676 c.sendAlert(alertHandshakeFailure)
677 return false, errors.New("tls: client does not support uncompressed connections")
678 }
David Benjamin7d79f832016-07-04 09:20:45 -0700679
680 if err := hs.processClientExtensions(&hs.hello.extensions); err != nil {
681 return false, err
Adam Langley09505632015-07-30 18:10:13 -0700682 }
Adam Langley95c29f32014-06-20 12:00:00 -0700683
684 supportedCurve := false
685 preferredCurves := config.curvePreferences()
686Curves:
687 for _, curve := range hs.clientHello.supportedCurves {
688 for _, supported := range preferredCurves {
689 if supported == curve {
690 supportedCurve = true
691 break Curves
692 }
693 }
694 }
695
696 supportedPointFormat := false
697 for _, pointFormat := range hs.clientHello.supportedPoints {
698 if pointFormat == pointFormatUncompressed {
699 supportedPointFormat = true
700 break
701 }
702 }
703 hs.ellipticOk = supportedCurve && supportedPointFormat
704
Adam Langley95c29f32014-06-20 12:00:00 -0700705 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
706
David Benjamin4b27d9f2015-05-12 22:42:52 -0400707 // For test purposes, check that the peer never offers a session when
708 // renegotiating.
709 if c.cipherSuite != nil && len(hs.clientHello.sessionId) > 0 && c.config.Bugs.FailIfResumeOnRenego {
710 return false, errors.New("tls: offered resumption on renegotiation")
711 }
712
David Benjamindd6fed92015-10-23 17:41:12 -0400713 if c.config.Bugs.FailIfSessionOffered && (len(hs.clientHello.sessionTicket) > 0 || len(hs.clientHello.sessionId) > 0) {
714 return false, errors.New("tls: client offered a session ticket or ID")
715 }
716
Adam Langley95c29f32014-06-20 12:00:00 -0700717 if hs.checkForResumption() {
718 return true, nil
719 }
720
Adam Langley95c29f32014-06-20 12:00:00 -0700721 var preferenceList, supportedList []uint16
722 if c.config.PreferServerCipherSuites {
723 preferenceList = c.config.cipherSuites()
724 supportedList = hs.clientHello.cipherSuites
725 } else {
726 preferenceList = hs.clientHello.cipherSuites
727 supportedList = c.config.cipherSuites()
728 }
729
730 for _, id := range preferenceList {
Nick Harper728eed82016-07-07 17:36:52 -0700731 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk, true); hs.suite != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700732 break
733 }
734 }
735
736 if hs.suite == nil {
737 c.sendAlert(alertHandshakeFailure)
738 return false, errors.New("tls: no cipher suite supported by both client and server")
739 }
740
741 return false, nil
742}
743
David Benjamin7d79f832016-07-04 09:20:45 -0700744// processClientExtensions processes all ClientHello extensions not directly
745// related to cipher suite negotiation and writes responses in serverExtensions.
746func (hs *serverHandshakeState) processClientExtensions(serverExtensions *serverExtensions) error {
747 config := hs.c.config
748 c := hs.c
749
David Benjamin8d315d72016-07-18 01:03:18 +0200750 if c.vers < VersionTLS13 || config.Bugs.NegotiateRenegotiationInfoAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700751 if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) {
752 c.sendAlert(alertHandshakeFailure)
753 return errors.New("tls: renegotiation mismatch")
David Benjamin7d79f832016-07-04 09:20:45 -0700754 }
David Benjamin7d79f832016-07-04 09:20:45 -0700755
Nick Harper728eed82016-07-07 17:36:52 -0700756 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
757 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.clientVerify...)
758 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.serverVerify...)
759 if c.config.Bugs.BadRenegotiationInfo {
760 serverExtensions.secureRenegotiation[0] ^= 0x80
761 }
762 } else {
763 serverExtensions.secureRenegotiation = hs.clientHello.secureRenegotiation
764 }
765
766 if c.noRenegotiationInfo() {
767 serverExtensions.secureRenegotiation = nil
768 }
David Benjamin7d79f832016-07-04 09:20:45 -0700769 }
770
771 serverExtensions.duplicateExtension = c.config.Bugs.DuplicateExtension
772
773 if len(hs.clientHello.serverName) > 0 {
774 c.serverName = hs.clientHello.serverName
775 }
776 if len(config.Certificates) == 0 {
777 c.sendAlert(alertInternalError)
778 return errors.New("tls: no certificates configured")
779 }
780 hs.cert = &config.Certificates[0]
781 if len(hs.clientHello.serverName) > 0 {
782 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
783 }
784 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
785 return errors.New("tls: unexpected server name")
786 }
787
788 if len(hs.clientHello.alpnProtocols) > 0 {
789 if proto := c.config.Bugs.ALPNProtocol; proto != nil {
790 serverExtensions.alpnProtocol = *proto
791 serverExtensions.alpnProtocolEmpty = len(*proto) == 0
792 c.clientProtocol = *proto
793 c.usedALPN = true
794 } else if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
795 serverExtensions.alpnProtocol = selectedProto
796 c.clientProtocol = selectedProto
797 c.usedALPN = true
798 }
799 }
Nick Harper728eed82016-07-07 17:36:52 -0700800
David Benjamin8d315d72016-07-18 01:03:18 +0200801 if c.vers < VersionTLS13 || config.Bugs.NegotiateNPNAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700802 if len(hs.clientHello.alpnProtocols) == 0 || c.config.Bugs.NegotiateALPNAndNPN {
803 // Although sending an empty NPN extension is reasonable, Firefox has
804 // had a bug around this. Best to send nothing at all if
805 // config.NextProtos is empty. See
806 // https://code.google.com/p/go/issues/detail?id=5445.
807 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
808 serverExtensions.nextProtoNeg = true
809 serverExtensions.nextProtos = config.NextProtos
810 serverExtensions.npnLast = config.Bugs.SwapNPNAndALPN
811 }
David Benjamin7d79f832016-07-04 09:20:45 -0700812 }
Steven Valdez143e8b32016-07-11 13:19:03 -0400813 }
David Benjamin7d79f832016-07-04 09:20:45 -0700814
David Benjamin8d315d72016-07-18 01:03:18 +0200815 if c.vers < VersionTLS13 || config.Bugs.NegotiateEMSAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700816 serverExtensions.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !c.config.Bugs.NoExtendedMasterSecret
Steven Valdez143e8b32016-07-11 13:19:03 -0400817 }
David Benjamin7d79f832016-07-04 09:20:45 -0700818
David Benjamin8d315d72016-07-18 01:03:18 +0200819 if c.vers < VersionTLS13 || config.Bugs.NegotiateChannelIDAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700820 if hs.clientHello.channelIDSupported && config.RequestChannelID {
821 serverExtensions.channelIDRequested = true
822 }
David Benjamin7d79f832016-07-04 09:20:45 -0700823 }
824
825 if hs.clientHello.srtpProtectionProfiles != nil {
826 SRTPLoop:
827 for _, p1 := range c.config.SRTPProtectionProfiles {
828 for _, p2 := range hs.clientHello.srtpProtectionProfiles {
829 if p1 == p2 {
830 serverExtensions.srtpProtectionProfile = p1
831 c.srtpProtectionProfile = p1
832 break SRTPLoop
833 }
834 }
835 }
836 }
837
838 if c.config.Bugs.SendSRTPProtectionProfile != 0 {
839 serverExtensions.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
840 }
841
842 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
843 if hs.clientHello.customExtension != *expected {
844 return fmt.Errorf("tls: bad custom extension contents %q", hs.clientHello.customExtension)
845 }
846 }
847 serverExtensions.customExtension = config.Bugs.CustomExtension
848
Steven Valdez143e8b32016-07-11 13:19:03 -0400849 if c.config.Bugs.AdvertiseTicketExtension {
850 serverExtensions.ticketSupported = true
851 }
852
David Benjamin7d79f832016-07-04 09:20:45 -0700853 return nil
854}
855
Adam Langley95c29f32014-06-20 12:00:00 -0700856// checkForResumption returns true if we should perform resumption on this connection.
857func (hs *serverHandshakeState) checkForResumption() bool {
858 c := hs.c
859
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500860 if len(hs.clientHello.sessionTicket) > 0 {
861 if c.config.SessionTicketsDisabled {
862 return false
863 }
David Benjaminb0c8db72014-09-24 15:19:56 -0400864
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500865 var ok bool
866 if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
867 return false
868 }
869 } else {
870 if c.config.ServerSessionCache == nil {
871 return false
872 }
873
874 var ok bool
875 sessionId := string(hs.clientHello.sessionId)
876 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
877 return false
878 }
Adam Langley95c29f32014-06-20 12:00:00 -0700879 }
880
David Benjamine18d8212014-11-10 02:37:15 -0500881 // Never resume a session for a different SSL version.
882 if !c.config.Bugs.AllowSessionVersionMismatch && c.vers != hs.sessionState.vers {
883 return false
Adam Langley95c29f32014-06-20 12:00:00 -0700884 }
885
886 cipherSuiteOk := false
887 // Check that the client is still offering the ciphersuite in the session.
888 for _, id := range hs.clientHello.cipherSuites {
889 if id == hs.sessionState.cipherSuite {
890 cipherSuiteOk = true
891 break
892 }
893 }
894 if !cipherSuiteOk {
895 return false
896 }
897
898 // Check that we also support the ciphersuite from the session.
Nick Harper728eed82016-07-07 17:36:52 -0700899 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk, true)
Adam Langley95c29f32014-06-20 12:00:00 -0700900 if hs.suite == nil {
901 return false
902 }
903
904 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
905 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
906 if needClientCerts && !sessionHasClientCerts {
907 return false
908 }
909 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
910 return false
911 }
912
913 return true
914}
915
916func (hs *serverHandshakeState) doResumeHandshake() error {
917 c := hs.c
918
919 hs.hello.cipherSuite = hs.suite.id
David Benjaminece3de92015-03-16 18:02:20 -0400920 if c.config.Bugs.SendCipherSuite != 0 {
921 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
922 }
Adam Langley95c29f32014-06-20 12:00:00 -0700923 // We echo the client's session ID in the ServerHello to let it know
924 // that we're doing a resumption.
925 hs.hello.sessionId = hs.clientHello.sessionId
Nick Harperb3d51be2016-07-01 11:43:18 -0400926 hs.hello.extensions.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -0700927
David Benjamin80d1b352016-05-04 19:19:06 -0400928 if c.config.Bugs.SendSCTListOnResume != nil {
Nick Harperb3d51be2016-07-01 11:43:18 -0400929 hs.hello.extensions.sctList = c.config.Bugs.SendSCTListOnResume
David Benjamin80d1b352016-05-04 19:19:06 -0400930 }
931
Adam Langley95c29f32014-06-20 12:00:00 -0700932 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -0400933 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -0400934 hs.writeClientHash(hs.clientHello.marshal())
935 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700936
937 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
938
939 if len(hs.sessionState.certificates) > 0 {
940 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
941 return err
942 }
943 }
944
945 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -0700946 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700947
948 return nil
949}
950
951func (hs *serverHandshakeState) doFullHandshake() error {
952 config := hs.c.config
953 c := hs.c
954
David Benjamin48cae082014-10-27 01:06:24 -0400955 isPSK := hs.suite.flags&suitePSK != 0
956 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -0400957 hs.hello.extensions.ocspStapling = true
Adam Langley95c29f32014-06-20 12:00:00 -0700958 }
959
David Benjamin61f95272014-11-25 01:55:35 -0500960 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -0400961 hs.hello.extensions.sctList = hs.cert.SignedCertificateTimestampList
David Benjamin61f95272014-11-25 01:55:35 -0500962 }
963
Nick Harperb3d51be2016-07-01 11:43:18 -0400964 hs.hello.extensions.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
Adam Langley95c29f32014-06-20 12:00:00 -0700965 hs.hello.cipherSuite = hs.suite.id
David Benjamin6095de82014-12-27 01:50:38 -0500966 if config.Bugs.SendCipherSuite != 0 {
967 hs.hello.cipherSuite = config.Bugs.SendCipherSuite
968 }
Nick Harperb3d51be2016-07-01 11:43:18 -0400969 c.extendedMasterSecret = hs.hello.extensions.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700970
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500971 // Generate a session ID if we're to save the session.
Nick Harperb3d51be2016-07-01 11:43:18 -0400972 if !hs.hello.extensions.ticketSupported && config.ServerSessionCache != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500973 hs.hello.sessionId = make([]byte, 32)
974 if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
975 c.sendAlert(alertInternalError)
976 return errors.New("tls: short read from Rand: " + err.Error())
977 }
978 }
979
Adam Langley95c29f32014-06-20 12:00:00 -0700980 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400981 hs.writeClientHash(hs.clientHello.marshal())
982 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700983
984 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
985
David Benjamin48cae082014-10-27 01:06:24 -0400986 if !isPSK {
987 certMsg := new(certificateMsg)
David Benjamin8923c0b2015-06-07 11:42:34 -0400988 if !config.Bugs.EmptyCertificateList {
989 certMsg.certificates = hs.cert.Certificate
990 }
David Benjamin48cae082014-10-27 01:06:24 -0400991 if !config.Bugs.UnauthenticatedECDH {
David Benjaminbcb2d912015-02-24 23:45:43 -0500992 certMsgBytes := certMsg.marshal()
David Benjaminbcb2d912015-02-24 23:45:43 -0500993 hs.writeServerHash(certMsgBytes)
994 c.writeRecord(recordTypeHandshake, certMsgBytes)
David Benjamin48cae082014-10-27 01:06:24 -0400995 }
David Benjamin1c375dd2014-07-12 00:48:23 -0400996 }
Adam Langley95c29f32014-06-20 12:00:00 -0700997
Nick Harperb3d51be2016-07-01 11:43:18 -0400998 if hs.hello.extensions.ocspStapling && !c.config.Bugs.SkipCertificateStatus {
Adam Langley95c29f32014-06-20 12:00:00 -0700999 certStatus := new(certificateStatusMsg)
1000 certStatus.statusType = statusTypeOCSP
1001 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -04001002 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001003 c.writeRecord(recordTypeHandshake, certStatus.marshal())
1004 }
1005
1006 keyAgreement := hs.suite.ka(c.vers)
1007 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
1008 if err != nil {
1009 c.sendAlert(alertHandshakeFailure)
1010 return err
1011 }
David Benjamin9c651c92014-07-12 13:27:45 -04001012 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -04001013 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001014 c.writeRecord(recordTypeHandshake, skx.marshal())
1015 }
1016
1017 if config.ClientAuth >= RequestClientCert {
1018 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -04001019 certReq := &certificateRequestMsg{
1020 certificateTypes: config.ClientCertificateTypes,
1021 }
1022 if certReq.certificateTypes == nil {
1023 certReq.certificateTypes = []byte{
1024 byte(CertTypeRSASign),
1025 byte(CertTypeECDSASign),
1026 }
Adam Langley95c29f32014-06-20 12:00:00 -07001027 }
1028 if c.vers >= VersionTLS12 {
Nick Harper60edffd2016-06-21 15:19:24 -07001029 certReq.hasSignatureAlgorithm = true
1030 if !config.Bugs.NoSignatureAlgorithms {
David Benjamin7a41d372016-07-09 11:21:54 -07001031 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin000800a2014-11-14 01:43:59 -05001032 }
Adam Langley95c29f32014-06-20 12:00:00 -07001033 }
1034
1035 // An empty list of certificateAuthorities signals to
1036 // the client that it may send any certificate in response
1037 // to our request. When we know the CAs we trust, then
1038 // we can send them down, so that the client can choose
1039 // an appropriate certificate to give to us.
1040 if config.ClientCAs != nil {
1041 certReq.certificateAuthorities = config.ClientCAs.Subjects()
1042 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001043 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001044 c.writeRecord(recordTypeHandshake, certReq.marshal())
1045 }
1046
1047 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001048 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001049 c.writeRecord(recordTypeHandshake, helloDone.marshal())
David Benjamin582ba042016-07-07 12:33:25 -07001050 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001051
1052 var pub crypto.PublicKey // public key for client auth, if any
1053
David Benjamin83f90402015-01-27 01:09:43 -05001054 if err := c.simulatePacketLoss(nil); err != nil {
1055 return err
1056 }
Adam Langley95c29f32014-06-20 12:00:00 -07001057 msg, err := c.readHandshake()
1058 if err != nil {
1059 return err
1060 }
1061
1062 var ok bool
1063 // If we requested a client certificate, then the client must send a
1064 // certificate message, even if it's empty.
1065 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -04001066 var certMsg *certificateMsg
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001067 var certificates [][]byte
1068 if certMsg, ok = msg.(*certificateMsg); ok {
1069 if c.vers == VersionSSL30 && len(certMsg.certificates) == 0 {
1070 return errors.New("tls: empty certificate message in SSL 3.0")
1071 }
1072
1073 hs.writeClientHash(certMsg.marshal())
1074 certificates = certMsg.certificates
1075 } else if c.vers != VersionSSL30 {
1076 // In TLS, the Certificate message is required. In SSL
1077 // 3.0, the peer skips it when sending no certificates.
Adam Langley95c29f32014-06-20 12:00:00 -07001078 c.sendAlert(alertUnexpectedMessage)
1079 return unexpectedMessageError(certMsg, msg)
1080 }
Adam Langley95c29f32014-06-20 12:00:00 -07001081
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001082 if len(certificates) == 0 {
Adam Langley95c29f32014-06-20 12:00:00 -07001083 // The client didn't actually send a certificate
1084 switch config.ClientAuth {
1085 case RequireAnyClientCert, RequireAndVerifyClientCert:
1086 c.sendAlert(alertBadCertificate)
1087 return errors.New("tls: client didn't provide a certificate")
1088 }
1089 }
1090
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001091 pub, err = hs.processCertsFromClient(certificates)
Adam Langley95c29f32014-06-20 12:00:00 -07001092 if err != nil {
1093 return err
1094 }
1095
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001096 if ok {
1097 msg, err = c.readHandshake()
1098 if err != nil {
1099 return err
1100 }
Adam Langley95c29f32014-06-20 12:00:00 -07001101 }
1102 }
1103
1104 // Get client key exchange
1105 ckx, ok := msg.(*clientKeyExchangeMsg)
1106 if !ok {
1107 c.sendAlert(alertUnexpectedMessage)
1108 return unexpectedMessageError(ckx, msg)
1109 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001110 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001111
David Benjamine098ec22014-08-27 23:13:20 -04001112 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
1113 if err != nil {
1114 c.sendAlert(alertHandshakeFailure)
1115 return err
1116 }
Adam Langley75712922014-10-10 16:23:43 -07001117 if c.extendedMasterSecret {
1118 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1119 } else {
1120 if c.config.Bugs.RequireExtendedMasterSecret {
1121 return errors.New("tls: extended master secret required but not supported by peer")
1122 }
1123 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
1124 }
David Benjamine098ec22014-08-27 23:13:20 -04001125
Adam Langley95c29f32014-06-20 12:00:00 -07001126 // If we received a client cert in response to our certificate request message,
1127 // the client will send us a certificateVerifyMsg immediately after the
1128 // clientKeyExchangeMsg. This message is a digest of all preceding
1129 // handshake-layer messages that is signed using the private key corresponding
1130 // to the client's certificate. This allows us to verify that the client is in
1131 // possession of the private key of the certificate.
1132 if len(c.peerCertificates) > 0 {
1133 msg, err = c.readHandshake()
1134 if err != nil {
1135 return err
1136 }
1137 certVerify, ok := msg.(*certificateVerifyMsg)
1138 if !ok {
1139 c.sendAlert(alertUnexpectedMessage)
1140 return unexpectedMessageError(certVerify, msg)
1141 }
1142
David Benjaminde620d92014-07-18 15:03:41 -04001143 // Determine the signature type.
Nick Harper60edffd2016-06-21 15:19:24 -07001144 var sigAlg signatureAlgorithm
1145 if certVerify.hasSignatureAlgorithm {
1146 sigAlg = certVerify.signatureAlgorithm
Nick Harper60edffd2016-06-21 15:19:24 -07001147 c.peerSignatureAlgorithm = sigAlg
David Benjaminde620d92014-07-18 15:03:41 -04001148 }
1149
Nick Harper60edffd2016-06-21 15:19:24 -07001150 if c.vers > VersionSSL30 {
David Benjamin1fb125c2016-07-08 18:52:12 -07001151 err = verifyMessage(c.vers, pub, c.config, sigAlg, hs.finishedHash.buffer, certVerify.signature)
Nick Harper60edffd2016-06-21 15:19:24 -07001152 } else {
1153 // SSL 3.0's client certificate construction is
1154 // incompatible with signatureAlgorithm.
1155 rsaPub, ok := pub.(*rsa.PublicKey)
1156 if !ok {
1157 err = errors.New("unsupported key type for client certificate")
1158 } else {
1159 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
1160 err = rsa.VerifyPKCS1v15(rsaPub, crypto.MD5SHA1, digest, certVerify.signature)
David Benjaminde620d92014-07-18 15:03:41 -04001161 }
Adam Langley95c29f32014-06-20 12:00:00 -07001162 }
1163 if err != nil {
1164 c.sendAlert(alertBadCertificate)
1165 return errors.New("could not validate signature of connection nonces: " + err.Error())
1166 }
1167
David Benjamin83c0bc92014-08-04 01:23:53 -04001168 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001169 }
1170
David Benjamine098ec22014-08-27 23:13:20 -04001171 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001172
1173 return nil
1174}
1175
1176func (hs *serverHandshakeState) establishKeys() error {
1177 c := hs.c
1178
1179 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001180 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen(c.vers))
Adam Langley95c29f32014-06-20 12:00:00 -07001181
1182 var clientCipher, serverCipher interface{}
1183 var clientHash, serverHash macFunction
1184
1185 if hs.suite.aead == nil {
1186 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
1187 clientHash = hs.suite.mac(c.vers, clientMAC)
1188 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
1189 serverHash = hs.suite.mac(c.vers, serverMAC)
1190 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001191 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1192 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001193 }
1194
1195 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
1196 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
1197
1198 return nil
1199}
1200
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001201func (hs *serverHandshakeState) readFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001202 c := hs.c
1203
1204 c.readRecord(recordTypeChangeCipherSpec)
1205 if err := c.in.error(); err != nil {
1206 return err
1207 }
1208
Nick Harperb3d51be2016-07-01 11:43:18 -04001209 if hs.hello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001210 msg, err := c.readHandshake()
1211 if err != nil {
1212 return err
1213 }
1214 nextProto, ok := msg.(*nextProtoMsg)
1215 if !ok {
1216 c.sendAlert(alertUnexpectedMessage)
1217 return unexpectedMessageError(nextProto, msg)
1218 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001219 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001220 c.clientProtocol = nextProto.proto
1221 }
1222
Nick Harperb3d51be2016-07-01 11:43:18 -04001223 if hs.hello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001224 msg, err := c.readHandshake()
1225 if err != nil {
1226 return err
1227 }
David Benjamin24599a82016-06-30 18:56:53 -04001228 channelIDMsg, ok := msg.(*channelIDMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001229 if !ok {
1230 c.sendAlert(alertUnexpectedMessage)
David Benjamin24599a82016-06-30 18:56:53 -04001231 return unexpectedMessageError(channelIDMsg, msg)
David Benjamind30a9902014-08-24 01:44:23 -04001232 }
David Benjamin24599a82016-06-30 18:56:53 -04001233 x := new(big.Int).SetBytes(channelIDMsg.channelID[0:32])
1234 y := new(big.Int).SetBytes(channelIDMsg.channelID[32:64])
1235 r := new(big.Int).SetBytes(channelIDMsg.channelID[64:96])
1236 s := new(big.Int).SetBytes(channelIDMsg.channelID[96:128])
David Benjamind30a9902014-08-24 01:44:23 -04001237 if !elliptic.P256().IsOnCurve(x, y) {
1238 return errors.New("tls: invalid channel ID public key")
1239 }
1240 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
1241 var resumeHash []byte
1242 if isResume {
1243 resumeHash = hs.sessionState.handshakeHash
1244 }
1245 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
1246 return errors.New("tls: invalid channel ID signature")
1247 }
1248 c.channelID = channelID
1249
David Benjamin24599a82016-06-30 18:56:53 -04001250 hs.writeClientHash(channelIDMsg.marshal())
David Benjamind30a9902014-08-24 01:44:23 -04001251 }
1252
Adam Langley95c29f32014-06-20 12:00:00 -07001253 msg, err := c.readHandshake()
1254 if err != nil {
1255 return err
1256 }
1257 clientFinished, ok := msg.(*finishedMsg)
1258 if !ok {
1259 c.sendAlert(alertUnexpectedMessage)
1260 return unexpectedMessageError(clientFinished, msg)
1261 }
1262
1263 verify := hs.finishedHash.clientSum(hs.masterSecret)
1264 if len(verify) != len(clientFinished.verifyData) ||
1265 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
1266 c.sendAlert(alertHandshakeFailure)
1267 return errors.New("tls: client's Finished message is incorrect")
1268 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001269 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001270 copy(out, clientFinished.verifyData)
Adam Langley95c29f32014-06-20 12:00:00 -07001271
David Benjamin83c0bc92014-08-04 01:23:53 -04001272 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001273 return nil
1274}
1275
1276func (hs *serverHandshakeState) sendSessionTicket() error {
Adam Langley95c29f32014-06-20 12:00:00 -07001277 c := hs.c
Adam Langley95c29f32014-06-20 12:00:00 -07001278 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -04001279 vers: c.vers,
1280 cipherSuite: hs.suite.id,
1281 masterSecret: hs.masterSecret,
1282 certificates: hs.certsFromClient,
1283 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -07001284 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001285
Nick Harperb3d51be2016-07-01 11:43:18 -04001286 if !hs.hello.extensions.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001287 if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
1288 c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
1289 }
1290 return nil
1291 }
1292
1293 m := new(newSessionTicketMsg)
1294
David Benjamindd6fed92015-10-23 17:41:12 -04001295 if !c.config.Bugs.SendEmptySessionTicket {
1296 var err error
1297 m.ticket, err = c.encryptTicket(&state)
1298 if err != nil {
1299 return err
1300 }
Adam Langley95c29f32014-06-20 12:00:00 -07001301 }
Adam Langley95c29f32014-06-20 12:00:00 -07001302
David Benjamin83c0bc92014-08-04 01:23:53 -04001303 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001304 c.writeRecord(recordTypeHandshake, m.marshal())
1305
1306 return nil
1307}
1308
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001309func (hs *serverHandshakeState) sendFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001310 c := hs.c
1311
David Benjamin86271ee2014-07-21 16:14:03 -04001312 finished := new(finishedMsg)
1313 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001314 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001315 if c.config.Bugs.BadFinished {
1316 finished.verifyData[0]++
1317 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001318 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001319 hs.finishedBytes = finished.marshal()
1320 hs.writeServerHash(hs.finishedBytes)
1321 postCCSBytes := hs.finishedBytes
David Benjamin86271ee2014-07-21 16:14:03 -04001322
1323 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
1324 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
1325 postCCSBytes = postCCSBytes[5:]
David Benjamin61672812016-07-14 23:10:43 -04001326 } else if c.config.Bugs.SendUnencryptedFinished {
1327 c.writeRecord(recordTypeHandshake, postCCSBytes)
1328 postCCSBytes = nil
David Benjamin86271ee2014-07-21 16:14:03 -04001329 }
David Benjamin582ba042016-07-07 12:33:25 -07001330 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001331
David Benjamina0e52232014-07-19 17:39:58 -04001332 if !c.config.Bugs.SkipChangeCipherSpec {
David Benjamin8411b242015-11-26 12:07:28 -05001333 ccs := []byte{1}
1334 if c.config.Bugs.BadChangeCipherSpec != nil {
1335 ccs = c.config.Bugs.BadChangeCipherSpec
1336 }
1337 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamina0e52232014-07-19 17:39:58 -04001338 }
Adam Langley95c29f32014-06-20 12:00:00 -07001339
David Benjamin4189bd92015-01-25 23:52:39 -05001340 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1341 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1342 }
David Benjamindc3da932015-03-12 15:09:02 -04001343 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1344 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1345 return errors.New("tls: simulating post-CCS alert")
1346 }
David Benjamin4189bd92015-01-25 23:52:39 -05001347
David Benjamin61672812016-07-14 23:10:43 -04001348 if !c.config.Bugs.SkipFinished && len(postCCSBytes) > 0 {
David Benjaminb80168e2015-02-08 18:30:14 -05001349 c.writeRecord(recordTypeHandshake, postCCSBytes)
David Benjamin582ba042016-07-07 12:33:25 -07001350 c.flushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -05001351 }
Adam Langley95c29f32014-06-20 12:00:00 -07001352
David Benjaminc565ebb2015-04-03 04:06:36 -04001353 c.cipherSuite = hs.suite
Adam Langley95c29f32014-06-20 12:00:00 -07001354
1355 return nil
1356}
1357
1358// processCertsFromClient takes a chain of client certificates either from a
1359// Certificates message or from a sessionState and verifies them. It returns
1360// the public key of the leaf certificate.
1361func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
1362 c := hs.c
1363
1364 hs.certsFromClient = certificates
1365 certs := make([]*x509.Certificate, len(certificates))
1366 var err error
1367 for i, asn1Data := range certificates {
1368 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
1369 c.sendAlert(alertBadCertificate)
1370 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
1371 }
1372 }
1373
1374 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
1375 opts := x509.VerifyOptions{
1376 Roots: c.config.ClientCAs,
1377 CurrentTime: c.config.time(),
1378 Intermediates: x509.NewCertPool(),
1379 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
1380 }
1381
1382 for _, cert := range certs[1:] {
1383 opts.Intermediates.AddCert(cert)
1384 }
1385
1386 chains, err := certs[0].Verify(opts)
1387 if err != nil {
1388 c.sendAlert(alertBadCertificate)
1389 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
1390 }
1391
1392 ok := false
1393 for _, ku := range certs[0].ExtKeyUsage {
1394 if ku == x509.ExtKeyUsageClientAuth {
1395 ok = true
1396 break
1397 }
1398 }
1399 if !ok {
1400 c.sendAlert(alertHandshakeFailure)
1401 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
1402 }
1403
1404 c.verifiedChains = chains
1405 }
1406
1407 if len(certs) > 0 {
1408 var pub crypto.PublicKey
1409 switch key := certs[0].PublicKey.(type) {
1410 case *ecdsa.PublicKey, *rsa.PublicKey:
1411 pub = key
1412 default:
1413 c.sendAlert(alertUnsupportedCertificate)
1414 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
1415 }
1416 c.peerCertificates = certs
1417 return pub, nil
1418 }
1419
1420 return nil, nil
1421}
1422
David Benjamin83c0bc92014-08-04 01:23:53 -04001423func (hs *serverHandshakeState) writeServerHash(msg []byte) {
1424 // writeServerHash is called before writeRecord.
1425 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1426}
1427
1428func (hs *serverHandshakeState) writeClientHash(msg []byte) {
1429 // writeClientHash is called after readHandshake.
1430 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1431}
1432
1433func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
1434 if hs.c.isDTLS {
1435 // This is somewhat hacky. DTLS hashes a slightly different format.
1436 // First, the TLS header.
1437 hs.finishedHash.Write(msg[:4])
1438 // Then the sequence number and reassembled fragment offset (always 0).
1439 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1440 // Then the reassembled fragment (always equal to the message length).
1441 hs.finishedHash.Write(msg[1:4])
1442 // And then the message body.
1443 hs.finishedHash.Write(msg[4:])
1444 } else {
1445 hs.finishedHash.Write(msg)
1446 }
1447}
1448
Adam Langley95c29f32014-06-20 12:00:00 -07001449// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
1450// is acceptable to use.
Nick Harper728eed82016-07-07 17:36:52 -07001451func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk, pskOk bool) *cipherSuite {
Adam Langley95c29f32014-06-20 12:00:00 -07001452 for _, supported := range supportedCipherSuites {
1453 if id == supported {
1454 var candidate *cipherSuite
1455
1456 for _, s := range cipherSuites {
1457 if s.id == id {
1458 candidate = s
1459 break
1460 }
1461 }
1462 if candidate == nil {
1463 continue
1464 }
1465 // Don't select a ciphersuite which we can't
1466 // support for this client.
David Benjamin0407e762016-06-17 16:41:18 -04001467 if !c.config.Bugs.EnableAllCiphers {
Nick Harper728eed82016-07-07 17:36:52 -07001468 if (candidate.flags&suitePSK != 0) && !pskOk {
1469 continue
1470 }
David Benjamin0407e762016-06-17 16:41:18 -04001471 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
1472 continue
1473 }
1474 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
1475 continue
1476 }
1477 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
1478 continue
1479 }
Nick Harper728eed82016-07-07 17:36:52 -07001480 if version >= VersionTLS13 && candidate.flags&suiteTLS13 == 0 {
1481 continue
1482 }
David Benjamin0407e762016-06-17 16:41:18 -04001483 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
1484 continue
1485 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001486 }
Adam Langley95c29f32014-06-20 12:00:00 -07001487 return candidate
1488 }
1489 }
1490
1491 return nil
1492}
David Benjaminf93995b2015-11-05 18:23:20 -05001493
1494func isTLS12Cipher(id uint16) bool {
1495 for _, cipher := range cipherSuites {
1496 if cipher.id != id {
1497 continue
1498 }
1499 return cipher.flags&suiteTLS12 != 0
1500 }
1501 // Unknown cipher.
1502 return false
1503}