blob: 1c51799cba5a20776495e48a177c885b8a1a1311 [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() {
David Benjamin02edcd02016-07-27 17:40:37 -040087 c.sendHandshakeSeq--
Nick Harper728eed82016-07-07 17:36:52 -070088 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
89 c.flushHandshake()
90 }); err != nil {
91 return err
92 }
93 if err := hs.readFinished(nil, isResume); err != nil {
94 return err
95 }
96 c.didResume = true
97 } else {
98 // The client didn't include a session ticket, or it wasn't
99 // valid so we do a full handshake.
100 if err := hs.doFullHandshake(); err != nil {
101 return err
102 }
103 if err := hs.establishKeys(); err != nil {
104 return err
105 }
106 if err := hs.readFinished(c.firstFinished[:], isResume); err != nil {
107 return err
108 }
109 if c.config.Bugs.AlertBeforeFalseStartTest != 0 {
110 c.sendAlert(c.config.Bugs.AlertBeforeFalseStartTest)
111 }
112 if c.config.Bugs.ExpectFalseStart {
113 if err := c.readRecord(recordTypeApplicationData); err != nil {
114 return fmt.Errorf("tls: peer did not false start: %s", err)
115 }
116 }
David Benjaminbed9aae2014-08-07 19:13:38 -0400117 if err := hs.sendSessionTicket(); err != nil {
118 return err
119 }
Nick Harper728eed82016-07-07 17:36:52 -0700120 if err := hs.sendFinished(nil); err != nil {
121 return err
David Benjamine58c4f52014-08-24 03:47:07 -0400122 }
123 }
David Benjamin97a0a082016-07-13 17:57:35 -0400124
125 c.exporterSecret = hs.masterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700126 }
127 c.handshakeComplete = true
David Benjaminc565ebb2015-04-03 04:06:36 -0400128 copy(c.clientRandom[:], hs.clientHello.random)
129 copy(c.serverRandom[:], hs.hello.random)
Adam Langley95c29f32014-06-20 12:00:00 -0700130
131 return nil
132}
133
David Benjaminf25dda92016-07-04 10:05:26 -0700134// readClientHello reads a ClientHello message from the client and determines
135// the protocol version.
136func (hs *serverHandshakeState) readClientHello() error {
Adam Langley95c29f32014-06-20 12:00:00 -0700137 config := hs.c.config
138 c := hs.c
139
David Benjamin83f90402015-01-27 01:09:43 -0500140 if err := c.simulatePacketLoss(nil); err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700141 return err
David Benjamin83f90402015-01-27 01:09:43 -0500142 }
Adam Langley95c29f32014-06-20 12:00:00 -0700143 msg, err := c.readHandshake()
144 if err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700145 return err
Adam Langley95c29f32014-06-20 12:00:00 -0700146 }
147 var ok bool
148 hs.clientHello, ok = msg.(*clientHelloMsg)
149 if !ok {
150 c.sendAlert(alertUnexpectedMessage)
David Benjaminf25dda92016-07-04 10:05:26 -0700151 return unexpectedMessageError(hs.clientHello, msg)
Adam Langley95c29f32014-06-20 12:00:00 -0700152 }
Adam Langley33ad2b52015-07-20 17:43:53 -0700153 if size := config.Bugs.RequireClientHelloSize; size != 0 && len(hs.clientHello.raw) != size {
David Benjaminf25dda92016-07-04 10:05:26 -0700154 return fmt.Errorf("tls: ClientHello record size is %d, but expected %d", len(hs.clientHello.raw), size)
Feng Lu41aa3252014-11-21 22:47:56 -0800155 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400156
157 if c.isDTLS && !config.Bugs.SkipHelloVerifyRequest {
David Benjamin8bc38f52014-08-16 12:07:27 -0400158 // Per RFC 6347, the version field in HelloVerifyRequest SHOULD
159 // be always DTLS 1.0
David Benjamin83c0bc92014-08-04 01:23:53 -0400160 helloVerifyRequest := &helloVerifyRequestMsg{
David Benjamin8bc38f52014-08-16 12:07:27 -0400161 vers: VersionTLS10,
David Benjamin83c0bc92014-08-04 01:23:53 -0400162 cookie: make([]byte, 32),
163 }
164 if _, err := io.ReadFull(c.config.rand(), helloVerifyRequest.cookie); err != nil {
165 c.sendAlert(alertInternalError)
David Benjaminf25dda92016-07-04 10:05:26 -0700166 return errors.New("dtls: short read from Rand: " + err.Error())
David Benjamin83c0bc92014-08-04 01:23:53 -0400167 }
168 c.writeRecord(recordTypeHandshake, helloVerifyRequest.marshal())
David Benjamin582ba042016-07-07 12:33:25 -0700169 c.flushHandshake()
David Benjamin83c0bc92014-08-04 01:23:53 -0400170
David Benjamin83f90402015-01-27 01:09:43 -0500171 if err := c.simulatePacketLoss(nil); err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700172 return err
David Benjamin83f90402015-01-27 01:09:43 -0500173 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400174 msg, err := c.readHandshake()
175 if err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700176 return err
David Benjamin83c0bc92014-08-04 01:23:53 -0400177 }
178 newClientHello, ok := msg.(*clientHelloMsg)
179 if !ok {
180 c.sendAlert(alertUnexpectedMessage)
David Benjaminf25dda92016-07-04 10:05:26 -0700181 return unexpectedMessageError(hs.clientHello, msg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400182 }
183 if !bytes.Equal(newClientHello.cookie, helloVerifyRequest.cookie) {
David Benjaminf25dda92016-07-04 10:05:26 -0700184 return errors.New("dtls: invalid cookie")
David Benjamin83c0bc92014-08-04 01:23:53 -0400185 }
David Benjaminf2fedef2014-08-16 01:37:34 -0400186
187 // Apart from the cookie, the two ClientHellos must
188 // match. Note that clientHello.equal compares the
189 // serialization, so we make a copy.
190 oldClientHelloCopy := *hs.clientHello
191 oldClientHelloCopy.raw = nil
192 oldClientHelloCopy.cookie = nil
193 newClientHelloCopy := *newClientHello
194 newClientHelloCopy.raw = nil
195 newClientHelloCopy.cookie = nil
196 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
David Benjaminf25dda92016-07-04 10:05:26 -0700197 return errors.New("dtls: retransmitted ClientHello does not match")
David Benjamin83c0bc92014-08-04 01:23:53 -0400198 }
199 hs.clientHello = newClientHello
200 }
201
David Benjaminc44b1df2014-11-23 12:11:01 -0500202 if config.Bugs.RequireSameRenegoClientVersion && c.clientVersion != 0 {
203 if c.clientVersion != hs.clientHello.vers {
David Benjaminf25dda92016-07-04 10:05:26 -0700204 return fmt.Errorf("tls: client offered different version on renego")
David Benjaminc44b1df2014-11-23 12:11:01 -0500205 }
206 }
207 c.clientVersion = hs.clientHello.vers
208
David Benjamin6ae7f072015-01-26 10:22:13 -0500209 // Reject < 1.2 ClientHellos with signature_algorithms.
Nick Harper60edffd2016-06-21 15:19:24 -0700210 if c.clientVersion < VersionTLS12 && len(hs.clientHello.signatureAlgorithms) > 0 {
David Benjaminf25dda92016-07-04 10:05:26 -0700211 return fmt.Errorf("tls: client included signature_algorithms before TLS 1.2")
David Benjamin72dc7832015-03-16 17:49:43 -0400212 }
David Benjamin6ae7f072015-01-26 10:22:13 -0500213
David Benjaminf93995b2015-11-05 18:23:20 -0500214 // Check the client cipher list is consistent with the version.
215 if hs.clientHello.vers < VersionTLS12 {
216 for _, id := range hs.clientHello.cipherSuites {
217 if isTLS12Cipher(id) {
David Benjaminf25dda92016-07-04 10:05:26 -0700218 return fmt.Errorf("tls: client offered TLS 1.2 cipher before TLS 1.2")
David Benjaminf93995b2015-11-05 18:23:20 -0500219 }
220 }
221 }
222
David Benjamin405da482016-08-08 17:25:07 -0400223 if config.Bugs.ExpectNoTLS12Session {
224 if len(hs.clientHello.sessionId) > 0 {
225 return fmt.Errorf("tls: client offered an unexpected session ID")
226 }
227 if len(hs.clientHello.sessionTicket) > 0 {
228 return fmt.Errorf("tls: client offered an unexpected session ticket")
229 }
230 }
231
232 if config.Bugs.ExpectNoTLS13PSK && len(hs.clientHello.pskIdentities) > 0 {
233 return fmt.Errorf("tls: client offered unexpected PSK identities")
234 }
235
David Benjamin1f61f0d2016-07-10 12:20:35 -0400236 if config.Bugs.NegotiateVersion != 0 {
237 c.vers = config.Bugs.NegotiateVersion
David Benjamine7e36aa2016-08-08 12:39:41 -0400238 } else if c.haveVers && config.Bugs.NegotiateVersionOnRenego != 0 {
239 c.vers = config.Bugs.NegotiateVersionOnRenego
David Benjamin1f61f0d2016-07-10 12:20:35 -0400240 } else {
241 c.vers, ok = config.mutualVersion(hs.clientHello.vers, c.isDTLS)
242 if !ok {
243 c.sendAlert(alertProtocolVersion)
244 return fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
245 }
David Benjamin8bc38f52014-08-16 12:07:27 -0400246 }
Adam Langley95c29f32014-06-20 12:00:00 -0700247 c.haveVers = true
248
David Benjaminf25dda92016-07-04 10:05:26 -0700249 var scsvFound bool
250 for _, cipherSuite := range hs.clientHello.cipherSuites {
251 if cipherSuite == fallbackSCSV {
252 scsvFound = true
253 break
254 }
255 }
256
257 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
258 return errors.New("tls: no fallback SCSV found when expected")
259 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
260 return errors.New("tls: fallback SCSV found when not expected")
261 }
262
263 if config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
David Benjamin7a41d372016-07-09 11:21:54 -0700264 hs.clientHello.signatureAlgorithms = config.signSignatureAlgorithms()
David Benjaminf25dda92016-07-04 10:05:26 -0700265 }
266 if config.Bugs.IgnorePeerCurvePreferences {
267 hs.clientHello.supportedCurves = config.curvePreferences()
268 }
269 if config.Bugs.IgnorePeerCipherPreferences {
270 hs.clientHello.cipherSuites = config.cipherSuites()
271 }
272
273 return nil
274}
275
Nick Harper728eed82016-07-07 17:36:52 -0700276func (hs *serverHandshakeState) doTLS13Handshake() error {
277 c := hs.c
278 config := c.config
279
280 hs.hello = &serverHelloMsg{
281 isDTLS: c.isDTLS,
282 vers: c.vers,
283 }
284
Steven Valdez5440fe02016-07-18 12:40:30 -0400285 if config.Bugs.SendServerHelloVersion != 0 {
286 hs.hello.vers = config.Bugs.SendServerHelloVersion
287 }
288
Nick Harper728eed82016-07-07 17:36:52 -0700289 hs.hello.random = make([]byte, 32)
290 if _, err := io.ReadFull(config.rand(), hs.hello.random); err != nil {
291 c.sendAlert(alertInternalError)
292 return err
293 }
294
295 // TLS 1.3 forbids clients from advertising any non-null compression.
296 if len(hs.clientHello.compressionMethods) != 1 || hs.clientHello.compressionMethods[0] != compressionNone {
297 return errors.New("tls: client sent compression method other than null for TLS 1.3")
298 }
299
300 // Prepare an EncryptedExtensions message, but do not send it yet.
301 encryptedExtensions := new(encryptedExtensionsMsg)
Steven Valdez143e8b32016-07-11 13:19:03 -0400302 encryptedExtensions.empty = config.Bugs.EmptyEncryptedExtensions
Nick Harper728eed82016-07-07 17:36:52 -0700303 if err := hs.processClientExtensions(&encryptedExtensions.extensions); err != nil {
304 return err
305 }
306
307 supportedCurve := false
308 var selectedCurve CurveID
309 preferredCurves := config.curvePreferences()
310Curves:
311 for _, curve := range hs.clientHello.supportedCurves {
312 for _, supported := range preferredCurves {
313 if supported == curve {
314 supportedCurve = true
315 selectedCurve = curve
316 break Curves
317 }
318 }
319 }
320
321 _, ecdsaOk := hs.cert.PrivateKey.(*ecdsa.PrivateKey)
322
David Benjamin405da482016-08-08 17:25:07 -0400323 pskIdentities := hs.clientHello.pskIdentities
324 if len(pskIdentities) == 0 && len(hs.clientHello.sessionTicket) > 0 && c.config.Bugs.AcceptAnySession {
325 pskIdentities = [][]uint8{hs.clientHello.sessionTicket}
326 }
327 for i, pskIdentity := range pskIdentities {
Nick Harper0b3625b2016-07-25 16:16:28 -0700328 sessionState, ok := c.decryptTicket(pskIdentity)
329 if !ok {
330 continue
331 }
David Benjamin405da482016-08-08 17:25:07 -0400332 if !config.Bugs.AcceptAnySession {
333 if sessionState.vers != c.vers && c.config.Bugs.AcceptAnySession {
334 continue
335 }
336 if sessionState.ticketFlags&ticketAllowDHEResumption == 0 {
337 continue
338 }
339 if sessionState.ticketExpiration.Before(c.config.time()) {
340 continue
341 }
Nick Harper0b3625b2016-07-25 16:16:28 -0700342 }
David Benjamin405da482016-08-08 17:25:07 -0400343
Nick Harper0b3625b2016-07-25 16:16:28 -0700344 suiteId := ecdhePSKSuite(sessionState.cipherSuite)
David Benjamin405da482016-08-08 17:25:07 -0400345
346 // Check the client offered the cipher.
347 clientCipherSuites := hs.clientHello.cipherSuites
348 if config.Bugs.AcceptAnySession {
349 clientCipherSuites = []uint16{suiteId}
350 }
351 suite := mutualCipherSuite(clientCipherSuites, suiteId)
352
353 // Check the cipher is enabled by the server.
Nick Harper0b3625b2016-07-25 16:16:28 -0700354 var found bool
355 for _, id := range config.cipherSuites() {
356 if id == sessionState.cipherSuite {
357 found = true
358 break
359 }
360 }
David Benjamin405da482016-08-08 17:25:07 -0400361
Nick Harper0b3625b2016-07-25 16:16:28 -0700362 if suite != nil && found {
363 hs.sessionState = sessionState
364 hs.suite = suite
365 hs.hello.hasPSKIdentity = true
366 hs.hello.pskIdentity = uint16(i)
367 c.didResume = true
368 break
369 }
Nick Harper728eed82016-07-07 17:36:52 -0700370 }
371
Nick Harper0b3625b2016-07-25 16:16:28 -0700372 // If not resuming, select the cipher suite.
373 if hs.suite == nil {
374 var preferenceList, supportedList []uint16
375 if config.PreferServerCipherSuites {
376 preferenceList = config.cipherSuites()
377 supportedList = hs.clientHello.cipherSuites
378 } else {
379 preferenceList = hs.clientHello.cipherSuites
380 supportedList = config.cipherSuites()
381 }
382
383 for _, id := range preferenceList {
384 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, supportedCurve, ecdsaOk, false); hs.suite != nil {
385 break
386 }
Nick Harper728eed82016-07-07 17:36:52 -0700387 }
388 }
389
390 if hs.suite == nil {
391 c.sendAlert(alertHandshakeFailure)
392 return errors.New("tls: no cipher suite supported by both client and server")
393 }
394
395 hs.hello.cipherSuite = hs.suite.id
Steven Valdez0ee2e112016-07-15 06:51:15 -0400396 if c.config.Bugs.SendCipherSuite != 0 {
397 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
398 }
399
Nick Harper728eed82016-07-07 17:36:52 -0700400 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
401 hs.finishedHash.discardHandshakeBuffer()
402 hs.writeClientHash(hs.clientHello.marshal())
403
404 // Resolve PSK and compute the early secret.
Nick Harper0b3625b2016-07-25 16:16:28 -0700405 var psk []byte
406 // The only way for hs.suite to be a PSK suite yet for there to be
407 // no sessionState is if config.Bugs.EnableAllCiphers is true and
408 // the test runner forced us to negotiated a PSK suite. It doesn't
409 // really matter what we do here so long as we continue the
410 // handshake and let the client error out.
411 if hs.suite.flags&suitePSK != 0 && hs.sessionState != nil {
412 psk = deriveResumptionPSK(hs.suite, hs.sessionState.masterSecret)
413 hs.finishedHash.setResumptionContext(deriveResumptionContext(hs.suite, hs.sessionState.masterSecret))
414 } else {
415 psk = hs.finishedHash.zeroSecret()
416 hs.finishedHash.setResumptionContext(hs.finishedHash.zeroSecret())
417 }
Nick Harper728eed82016-07-07 17:36:52 -0700418
419 earlySecret := hs.finishedHash.extractKey(hs.finishedHash.zeroSecret(), psk)
420
421 // Resolve ECDHE and compute the handshake secret.
422 var ecdheSecret []byte
Steven Valdez143e8b32016-07-11 13:19:03 -0400423 if hs.suite.flags&suiteECDHE != 0 && !config.Bugs.MissingKeyShare {
Nick Harper728eed82016-07-07 17:36:52 -0700424 // Look for the key share corresponding to our selected curve.
425 var selectedKeyShare *keyShareEntry
426 for i := range hs.clientHello.keyShares {
427 if hs.clientHello.keyShares[i].group == selectedCurve {
428 selectedKeyShare = &hs.clientHello.keyShares[i]
429 break
430 }
431 }
432
Steven Valdez5440fe02016-07-18 12:40:30 -0400433 sendHelloRetryRequest := selectedKeyShare == nil
434 if config.Bugs.UnnecessaryHelloRetryRequest {
435 sendHelloRetryRequest = true
436 }
437 if config.Bugs.SkipHelloRetryRequest {
438 sendHelloRetryRequest = false
439 }
440 if sendHelloRetryRequest {
441 firstTime := true
442 ResendHelloRetryRequest:
Nick Harperdcfbc672016-07-16 17:47:31 +0200443 // Send HelloRetryRequest.
444 helloRetryRequestMsg := helloRetryRequestMsg{
445 vers: c.vers,
446 cipherSuite: hs.hello.cipherSuite,
447 selectedGroup: selectedCurve,
448 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400449 if config.Bugs.SendHelloRetryRequestCurve != 0 {
450 helloRetryRequestMsg.selectedGroup = config.Bugs.SendHelloRetryRequestCurve
451 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200452 hs.writeServerHash(helloRetryRequestMsg.marshal())
453 c.writeRecord(recordTypeHandshake, helloRetryRequestMsg.marshal())
454
455 // Read new ClientHello.
456 newMsg, err := c.readHandshake()
457 if err != nil {
458 return err
459 }
460 newClientHello, ok := newMsg.(*clientHelloMsg)
461 if !ok {
462 c.sendAlert(alertUnexpectedMessage)
463 return unexpectedMessageError(newClientHello, newMsg)
464 }
465 hs.writeClientHash(newClientHello.marshal())
466
467 // Check that the new ClientHello matches the old ClientHello, except for
468 // the addition of the new KeyShareEntry at the end of the list, and
469 // removing the EarlyDataIndication extension (if present).
470 newKeyShares := newClientHello.keyShares
471 if len(newKeyShares) == 0 || newKeyShares[len(newKeyShares)-1].group != selectedCurve {
472 return errors.New("tls: KeyShare from HelloRetryRequest not present in new ClientHello")
473 }
474 oldClientHelloCopy := *hs.clientHello
475 oldClientHelloCopy.raw = nil
476 oldClientHelloCopy.hasEarlyData = false
477 oldClientHelloCopy.earlyDataContext = nil
478 newClientHelloCopy := *newClientHello
479 newClientHelloCopy.raw = nil
480 newClientHelloCopy.keyShares = newKeyShares[:len(newKeyShares)-1]
481 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
482 return errors.New("tls: new ClientHello does not match")
483 }
484
Steven Valdez5440fe02016-07-18 12:40:30 -0400485 if firstTime && config.Bugs.SecondHelloRetryRequest {
486 firstTime = false
487 goto ResendHelloRetryRequest
488 }
489
Nick Harperdcfbc672016-07-16 17:47:31 +0200490 selectedKeyShare = &newKeyShares[len(newKeyShares)-1]
Nick Harper728eed82016-07-07 17:36:52 -0700491 }
492
493 // Once a curve has been selected and a key share identified,
494 // the server needs to generate a public value and send it in
495 // the ServerHello.
Steven Valdez5440fe02016-07-18 12:40:30 -0400496 curve, ok := curveForCurveID(selectedCurve)
Nick Harper728eed82016-07-07 17:36:52 -0700497 if !ok {
498 panic("tls: server failed to look up curve ID")
499 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400500 c.curveID = selectedCurve
501
502 var peerKey []byte
503 if config.Bugs.SkipHelloRetryRequest {
504 // If skipping HelloRetryRequest, use a random key to
505 // avoid crashing.
506 curve2, _ := curveForCurveID(selectedCurve)
507 var err error
508 peerKey, err = curve2.offer(config.rand())
509 if err != nil {
510 return err
511 }
512 } else {
513 peerKey = selectedKeyShare.keyExchange
514 }
515
Nick Harper728eed82016-07-07 17:36:52 -0700516 var publicKey []byte
517 var err error
Steven Valdez5440fe02016-07-18 12:40:30 -0400518 publicKey, ecdheSecret, err = curve.accept(config.rand(), peerKey)
Nick Harper728eed82016-07-07 17:36:52 -0700519 if err != nil {
520 c.sendAlert(alertHandshakeFailure)
521 return err
522 }
523 hs.hello.hasKeyShare = true
Steven Valdez0ee2e112016-07-15 06:51:15 -0400524
Steven Valdez5440fe02016-07-18 12:40:30 -0400525 curveID := selectedCurve
Steven Valdez0ee2e112016-07-15 06:51:15 -0400526 if c.config.Bugs.SendCurve != 0 {
527 curveID = config.Bugs.SendCurve
528 }
529 if c.config.Bugs.InvalidECDHPoint {
530 publicKey[0] ^= 0xff
531 }
532
Nick Harper728eed82016-07-07 17:36:52 -0700533 hs.hello.keyShare = keyShareEntry{
Steven Valdez0ee2e112016-07-15 06:51:15 -0400534 group: curveID,
Nick Harper728eed82016-07-07 17:36:52 -0700535 keyExchange: publicKey,
536 }
Steven Valdez143e8b32016-07-11 13:19:03 -0400537
538 if config.Bugs.EncryptedExtensionsWithKeyShare {
539 encryptedExtensions.extensions.hasKeyShare = true
540 encryptedExtensions.extensions.keyShare = keyShareEntry{
541 group: curveID,
542 keyExchange: publicKey,
543 }
544 }
Nick Harper728eed82016-07-07 17:36:52 -0700545 } else {
546 ecdheSecret = hs.finishedHash.zeroSecret()
547 }
548
549 // Send unencrypted ServerHello.
550 hs.writeServerHash(hs.hello.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400551 if config.Bugs.PartialEncryptedExtensionsWithServerHello {
552 helloBytes := hs.hello.marshal()
553 toWrite := make([]byte, 0, len(helloBytes)+1)
554 toWrite = append(toWrite, helloBytes...)
555 toWrite = append(toWrite, typeEncryptedExtensions)
556 c.writeRecord(recordTypeHandshake, toWrite)
557 } else {
558 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
559 }
Nick Harper728eed82016-07-07 17:36:52 -0700560 c.flushHandshake()
561
562 // Compute the handshake secret.
563 handshakeSecret := hs.finishedHash.extractKey(earlySecret, ecdheSecret)
564
565 // Switch to handshake traffic keys.
566 handshakeTrafficSecret := hs.finishedHash.deriveSecret(handshakeSecret, handshakeTrafficLabel)
David Benjamin21c00282016-07-18 21:56:23 +0200567 c.out.useTrafficSecret(c.vers, hs.suite, handshakeTrafficSecret, handshakePhase, serverWrite)
568 c.in.useTrafficSecret(c.vers, hs.suite, handshakeTrafficSecret, handshakePhase, clientWrite)
Nick Harper728eed82016-07-07 17:36:52 -0700569
Nick Harper0b3625b2016-07-25 16:16:28 -0700570 if hs.suite.flags&suitePSK == 0 {
David Benjamin615119a2016-07-06 19:22:55 -0700571 if hs.clientHello.ocspStapling {
572 encryptedExtensions.extensions.ocspResponse = hs.cert.OCSPStaple
573 }
574 if hs.clientHello.sctListSupported {
575 encryptedExtensions.extensions.sctList = hs.cert.SignedCertificateTimestampList
576 }
577 }
578
Nick Harper728eed82016-07-07 17:36:52 -0700579 // Send EncryptedExtensions.
580 hs.writeServerHash(encryptedExtensions.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400581 if config.Bugs.PartialEncryptedExtensionsWithServerHello {
582 // The first byte has already been sent.
583 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()[1:])
584 } else {
585 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal())
586 }
Nick Harper728eed82016-07-07 17:36:52 -0700587
588 if hs.suite.flags&suitePSK == 0 {
589 if config.ClientAuth >= RequestClientCert {
David Benjamin8d343b42016-07-09 14:26:01 -0700590 // Request a client certificate
591 certReq := &certificateRequestMsg{
592 hasSignatureAlgorithm: true,
593 hasRequestContext: true,
594 }
595 if !config.Bugs.NoSignatureAlgorithms {
David Benjaminf74ec792016-07-13 21:18:49 -0400596 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin8d343b42016-07-09 14:26:01 -0700597 }
598
599 // An empty list of certificateAuthorities signals to
600 // the client that it may send any certificate in response
601 // to our request. When we know the CAs we trust, then
602 // we can send them down, so that the client can choose
603 // an appropriate certificate to give to us.
604 if config.ClientCAs != nil {
605 certReq.certificateAuthorities = config.ClientCAs.Subjects()
606 }
607 hs.writeServerHash(certReq.marshal())
608 c.writeRecord(recordTypeHandshake, certReq.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700609 }
610
611 certMsg := &certificateMsg{
612 hasRequestContext: true,
613 }
614 if !config.Bugs.EmptyCertificateList {
615 certMsg.certificates = hs.cert.Certificate
616 }
David Benjamin1edae6b2016-07-13 16:58:23 -0400617 certMsgBytes := certMsg.marshal()
David Benjamin1edae6b2016-07-13 16:58:23 -0400618 hs.writeServerHash(certMsgBytes)
619 c.writeRecord(recordTypeHandshake, certMsgBytes)
Nick Harper728eed82016-07-07 17:36:52 -0700620
621 certVerify := &certificateVerifyMsg{
622 hasSignatureAlgorithm: true,
623 }
624
625 // Determine the hash to sign.
626 privKey := hs.cert.PrivateKey
627
628 var err error
629 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, config, hs.clientHello.signatureAlgorithms)
630 if err != nil {
631 c.sendAlert(alertInternalError)
632 return err
633 }
634
635 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
636 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
637 if err != nil {
638 c.sendAlert(alertInternalError)
639 return err
640 }
641
Steven Valdez0ee2e112016-07-15 06:51:15 -0400642 if config.Bugs.SendSignatureAlgorithm != 0 {
643 certVerify.signatureAlgorithm = config.Bugs.SendSignatureAlgorithm
644 }
645
Nick Harper728eed82016-07-07 17:36:52 -0700646 hs.writeServerHash(certVerify.marshal())
647 c.writeRecord(recordTypeHandshake, certVerify.marshal())
Nick Harper0b3625b2016-07-25 16:16:28 -0700648 } else {
649 // Pick up certificates from the session instead.
650 // hs.sessionState may be nil if config.Bugs.EnableAllCiphers is
651 // true.
652 if hs.sessionState != nil && len(hs.sessionState.certificates) > 0 {
653 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
654 return err
655 }
656 }
Nick Harper728eed82016-07-07 17:36:52 -0700657 }
658
659 finished := new(finishedMsg)
660 finished.verifyData = hs.finishedHash.serverSum(handshakeTrafficSecret)
661 if config.Bugs.BadFinished {
662 finished.verifyData[0]++
663 }
664 hs.writeServerHash(finished.marshal())
665 c.writeRecord(recordTypeHandshake, finished.marshal())
David Benjamin02edcd02016-07-27 17:40:37 -0400666 if c.config.Bugs.SendExtraFinished {
667 c.writeRecord(recordTypeHandshake, finished.marshal())
668 }
Nick Harper728eed82016-07-07 17:36:52 -0700669 c.flushHandshake()
670
671 // The various secrets do not incorporate the client's final leg, so
672 // derive them now before updating the handshake context.
673 masterSecret := hs.finishedHash.extractKey(handshakeSecret, hs.finishedHash.zeroSecret())
674 trafficSecret := hs.finishedHash.deriveSecret(masterSecret, applicationTrafficLabel)
675
David Benjamin2aad4062016-07-14 23:15:40 -0400676 // Switch to application data keys on write. In particular, any alerts
677 // from the client certificate are sent over these keys.
David Benjamin21c00282016-07-18 21:56:23 +0200678 c.out.useTrafficSecret(c.vers, hs.suite, trafficSecret, applicationPhase, serverWrite)
David Benjamin2aad4062016-07-14 23:15:40 -0400679
Nick Harper728eed82016-07-07 17:36:52 -0700680 // If we requested a client certificate, then the client must send a
681 // certificate message, even if it's empty.
682 if config.ClientAuth >= RequestClientCert {
David Benjamin8d343b42016-07-09 14:26:01 -0700683 msg, err := c.readHandshake()
684 if err != nil {
685 return err
686 }
687
688 certMsg, ok := msg.(*certificateMsg)
689 if !ok {
690 c.sendAlert(alertUnexpectedMessage)
691 return unexpectedMessageError(certMsg, msg)
692 }
693 hs.writeClientHash(certMsg.marshal())
694
695 if len(certMsg.certificates) == 0 {
696 // The client didn't actually send a certificate
697 switch config.ClientAuth {
698 case RequireAnyClientCert, RequireAndVerifyClientCert:
699 c.sendAlert(alertBadCertificate)
700 return errors.New("tls: client didn't provide a certificate")
701 }
702 }
703
704 pub, err := hs.processCertsFromClient(certMsg.certificates)
705 if err != nil {
706 return err
707 }
708
709 if len(c.peerCertificates) > 0 {
710 msg, err = c.readHandshake()
711 if err != nil {
712 return err
713 }
714
715 certVerify, ok := msg.(*certificateVerifyMsg)
716 if !ok {
717 c.sendAlert(alertUnexpectedMessage)
718 return unexpectedMessageError(certVerify, msg)
719 }
720
David Benjaminf74ec792016-07-13 21:18:49 -0400721 c.peerSignatureAlgorithm = certVerify.signatureAlgorithm
David Benjamin8d343b42016-07-09 14:26:01 -0700722 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
723 if err := verifyMessage(c.vers, pub, config, certVerify.signatureAlgorithm, input, certVerify.signature); err != nil {
724 c.sendAlert(alertBadCertificate)
725 return err
726 }
727 hs.writeClientHash(certVerify.marshal())
728 }
Nick Harper728eed82016-07-07 17:36:52 -0700729 }
730
731 // Read the client Finished message.
732 msg, err := c.readHandshake()
733 if err != nil {
734 return err
735 }
736 clientFinished, ok := msg.(*finishedMsg)
737 if !ok {
738 c.sendAlert(alertUnexpectedMessage)
739 return unexpectedMessageError(clientFinished, msg)
740 }
741
742 verify := hs.finishedHash.clientSum(handshakeTrafficSecret)
743 if len(verify) != len(clientFinished.verifyData) ||
744 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
745 c.sendAlert(alertHandshakeFailure)
746 return errors.New("tls: client's Finished message was incorrect")
747 }
David Benjamin97a0a082016-07-13 17:57:35 -0400748 hs.writeClientHash(clientFinished.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700749
David Benjamin2aad4062016-07-14 23:15:40 -0400750 // Switch to application data keys on read.
David Benjamin21c00282016-07-18 21:56:23 +0200751 c.in.useTrafficSecret(c.vers, hs.suite, trafficSecret, applicationPhase, clientWrite)
Nick Harper728eed82016-07-07 17:36:52 -0700752
Nick Harper728eed82016-07-07 17:36:52 -0700753 c.cipherSuite = hs.suite
David Benjamin97a0a082016-07-13 17:57:35 -0400754 c.exporterSecret = hs.finishedHash.deriveSecret(masterSecret, exporterLabel)
David Benjamin58104882016-07-18 01:25:41 +0200755 c.resumptionSecret = hs.finishedHash.deriveSecret(masterSecret, resumptionLabel)
756
757 // TODO(davidben): Allow configuring the number of tickets sent for
758 // testing.
759 if !c.config.SessionTicketsDisabled {
760 ticketCount := 2
761 for i := 0; i < ticketCount; i++ {
762 c.SendNewSessionTicket()
763 }
764 }
Nick Harper728eed82016-07-07 17:36:52 -0700765 return nil
766}
767
David Benjaminf25dda92016-07-04 10:05:26 -0700768// processClientHello processes the ClientHello message from the client and
769// decides whether we will perform session resumption.
770func (hs *serverHandshakeState) processClientHello() (isResume bool, err error) {
771 config := hs.c.config
772 c := hs.c
773
774 hs.hello = &serverHelloMsg{
775 isDTLS: c.isDTLS,
776 vers: c.vers,
777 compressionMethod: compressionNone,
778 }
779
Steven Valdez5440fe02016-07-18 12:40:30 -0400780 if config.Bugs.SendServerHelloVersion != 0 {
781 hs.hello.vers = config.Bugs.SendServerHelloVersion
782 }
783
David Benjaminf25dda92016-07-04 10:05:26 -0700784 hs.hello.random = make([]byte, 32)
785 _, err = io.ReadFull(config.rand(), hs.hello.random)
786 if err != nil {
787 c.sendAlert(alertInternalError)
788 return false, err
789 }
David Benjamin1f61f0d2016-07-10 12:20:35 -0400790 // Signal downgrades in the server random, per draft-ietf-tls-tls13-14,
791 // section 6.3.1.2.
Nick Harper85f20c22016-07-04 10:11:59 -0700792 if c.vers <= VersionTLS12 && config.maxVersion(c.isDTLS) >= VersionTLS13 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400793 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS13)
Nick Harper85f20c22016-07-04 10:11:59 -0700794 }
795 if c.vers <= VersionTLS11 && config.maxVersion(c.isDTLS) == VersionTLS12 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400796 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS12)
Nick Harper85f20c22016-07-04 10:11:59 -0700797 }
David Benjaminf25dda92016-07-04 10:05:26 -0700798
799 foundCompression := false
800 // We only support null compression, so check that the client offered it.
801 for _, compression := range hs.clientHello.compressionMethods {
802 if compression == compressionNone {
803 foundCompression = true
804 break
805 }
806 }
807
808 if !foundCompression {
809 c.sendAlert(alertHandshakeFailure)
810 return false, errors.New("tls: client does not support uncompressed connections")
811 }
David Benjamin7d79f832016-07-04 09:20:45 -0700812
813 if err := hs.processClientExtensions(&hs.hello.extensions); err != nil {
814 return false, err
Adam Langley09505632015-07-30 18:10:13 -0700815 }
Adam Langley95c29f32014-06-20 12:00:00 -0700816
817 supportedCurve := false
818 preferredCurves := config.curvePreferences()
819Curves:
820 for _, curve := range hs.clientHello.supportedCurves {
821 for _, supported := range preferredCurves {
822 if supported == curve {
823 supportedCurve = true
824 break Curves
825 }
826 }
827 }
828
829 supportedPointFormat := false
830 for _, pointFormat := range hs.clientHello.supportedPoints {
831 if pointFormat == pointFormatUncompressed {
832 supportedPointFormat = true
833 break
834 }
835 }
836 hs.ellipticOk = supportedCurve && supportedPointFormat
837
Adam Langley95c29f32014-06-20 12:00:00 -0700838 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
839
David Benjamin4b27d9f2015-05-12 22:42:52 -0400840 // For test purposes, check that the peer never offers a session when
841 // renegotiating.
842 if c.cipherSuite != nil && len(hs.clientHello.sessionId) > 0 && c.config.Bugs.FailIfResumeOnRenego {
843 return false, errors.New("tls: offered resumption on renegotiation")
844 }
845
David Benjamindd6fed92015-10-23 17:41:12 -0400846 if c.config.Bugs.FailIfSessionOffered && (len(hs.clientHello.sessionTicket) > 0 || len(hs.clientHello.sessionId) > 0) {
847 return false, errors.New("tls: client offered a session ticket or ID")
848 }
849
Adam Langley95c29f32014-06-20 12:00:00 -0700850 if hs.checkForResumption() {
851 return true, nil
852 }
853
Adam Langley95c29f32014-06-20 12:00:00 -0700854 var preferenceList, supportedList []uint16
855 if c.config.PreferServerCipherSuites {
856 preferenceList = c.config.cipherSuites()
857 supportedList = hs.clientHello.cipherSuites
858 } else {
859 preferenceList = hs.clientHello.cipherSuites
860 supportedList = c.config.cipherSuites()
861 }
862
863 for _, id := range preferenceList {
Nick Harper728eed82016-07-07 17:36:52 -0700864 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk, true); hs.suite != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700865 break
866 }
867 }
868
869 if hs.suite == nil {
870 c.sendAlert(alertHandshakeFailure)
871 return false, errors.New("tls: no cipher suite supported by both client and server")
872 }
873
874 return false, nil
875}
876
David Benjamin7d79f832016-07-04 09:20:45 -0700877// processClientExtensions processes all ClientHello extensions not directly
878// related to cipher suite negotiation and writes responses in serverExtensions.
879func (hs *serverHandshakeState) processClientExtensions(serverExtensions *serverExtensions) error {
880 config := hs.c.config
881 c := hs.c
882
David Benjamin8d315d72016-07-18 01:03:18 +0200883 if c.vers < VersionTLS13 || config.Bugs.NegotiateRenegotiationInfoAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700884 if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) {
885 c.sendAlert(alertHandshakeFailure)
886 return errors.New("tls: renegotiation mismatch")
David Benjamin7d79f832016-07-04 09:20:45 -0700887 }
David Benjamin7d79f832016-07-04 09:20:45 -0700888
Nick Harper728eed82016-07-07 17:36:52 -0700889 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
890 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.clientVerify...)
891 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.serverVerify...)
892 if c.config.Bugs.BadRenegotiationInfo {
893 serverExtensions.secureRenegotiation[0] ^= 0x80
894 }
895 } else {
896 serverExtensions.secureRenegotiation = hs.clientHello.secureRenegotiation
897 }
898
899 if c.noRenegotiationInfo() {
900 serverExtensions.secureRenegotiation = nil
901 }
David Benjamin7d79f832016-07-04 09:20:45 -0700902 }
903
904 serverExtensions.duplicateExtension = c.config.Bugs.DuplicateExtension
905
906 if len(hs.clientHello.serverName) > 0 {
907 c.serverName = hs.clientHello.serverName
908 }
909 if len(config.Certificates) == 0 {
910 c.sendAlert(alertInternalError)
911 return errors.New("tls: no certificates configured")
912 }
913 hs.cert = &config.Certificates[0]
914 if len(hs.clientHello.serverName) > 0 {
915 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
916 }
917 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
918 return errors.New("tls: unexpected server name")
919 }
920
921 if len(hs.clientHello.alpnProtocols) > 0 {
922 if proto := c.config.Bugs.ALPNProtocol; proto != nil {
923 serverExtensions.alpnProtocol = *proto
924 serverExtensions.alpnProtocolEmpty = len(*proto) == 0
925 c.clientProtocol = *proto
926 c.usedALPN = true
927 } else if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
928 serverExtensions.alpnProtocol = selectedProto
929 c.clientProtocol = selectedProto
930 c.usedALPN = true
931 }
932 }
Nick Harper728eed82016-07-07 17:36:52 -0700933
David Benjamin0c40a962016-08-01 12:05:50 -0400934 if len(c.config.Bugs.SendALPN) > 0 {
935 serverExtensions.alpnProtocol = c.config.Bugs.SendALPN
936 }
937
David Benjamin8d315d72016-07-18 01:03:18 +0200938 if c.vers < VersionTLS13 || config.Bugs.NegotiateNPNAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700939 if len(hs.clientHello.alpnProtocols) == 0 || c.config.Bugs.NegotiateALPNAndNPN {
940 // Although sending an empty NPN extension is reasonable, Firefox has
941 // had a bug around this. Best to send nothing at all if
942 // config.NextProtos is empty. See
943 // https://code.google.com/p/go/issues/detail?id=5445.
944 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
945 serverExtensions.nextProtoNeg = true
946 serverExtensions.nextProtos = config.NextProtos
947 serverExtensions.npnLast = config.Bugs.SwapNPNAndALPN
948 }
David Benjamin7d79f832016-07-04 09:20:45 -0700949 }
Steven Valdez143e8b32016-07-11 13:19:03 -0400950 }
David Benjamin7d79f832016-07-04 09:20:45 -0700951
David Benjamin8d315d72016-07-18 01:03:18 +0200952 if c.vers < VersionTLS13 || config.Bugs.NegotiateEMSAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700953 serverExtensions.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !c.config.Bugs.NoExtendedMasterSecret
Steven Valdez143e8b32016-07-11 13:19:03 -0400954 }
David Benjamin7d79f832016-07-04 09:20:45 -0700955
David Benjamin8d315d72016-07-18 01:03:18 +0200956 if c.vers < VersionTLS13 || config.Bugs.NegotiateChannelIDAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700957 if hs.clientHello.channelIDSupported && config.RequestChannelID {
958 serverExtensions.channelIDRequested = true
959 }
David Benjamin7d79f832016-07-04 09:20:45 -0700960 }
961
962 if hs.clientHello.srtpProtectionProfiles != nil {
963 SRTPLoop:
964 for _, p1 := range c.config.SRTPProtectionProfiles {
965 for _, p2 := range hs.clientHello.srtpProtectionProfiles {
966 if p1 == p2 {
967 serverExtensions.srtpProtectionProfile = p1
968 c.srtpProtectionProfile = p1
969 break SRTPLoop
970 }
971 }
972 }
973 }
974
975 if c.config.Bugs.SendSRTPProtectionProfile != 0 {
976 serverExtensions.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
977 }
978
979 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
980 if hs.clientHello.customExtension != *expected {
981 return fmt.Errorf("tls: bad custom extension contents %q", hs.clientHello.customExtension)
982 }
983 }
984 serverExtensions.customExtension = config.Bugs.CustomExtension
985
Steven Valdez143e8b32016-07-11 13:19:03 -0400986 if c.config.Bugs.AdvertiseTicketExtension {
987 serverExtensions.ticketSupported = true
988 }
989
David Benjamin7d79f832016-07-04 09:20:45 -0700990 return nil
991}
992
Adam Langley95c29f32014-06-20 12:00:00 -0700993// checkForResumption returns true if we should perform resumption on this connection.
994func (hs *serverHandshakeState) checkForResumption() bool {
995 c := hs.c
996
David Benjamin405da482016-08-08 17:25:07 -0400997 ticket := hs.clientHello.sessionTicket
998 if len(ticket) == 0 && len(hs.clientHello.pskIdentities) > 0 && c.config.Bugs.AcceptAnySession {
999 ticket = hs.clientHello.pskIdentities[0]
1000 }
1001 if len(ticket) > 0 {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001002 if c.config.SessionTicketsDisabled {
1003 return false
1004 }
David Benjaminb0c8db72014-09-24 15:19:56 -04001005
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001006 var ok bool
David Benjamin405da482016-08-08 17:25:07 -04001007 if hs.sessionState, ok = c.decryptTicket(ticket); !ok {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001008 return false
1009 }
1010 } else {
1011 if c.config.ServerSessionCache == nil {
1012 return false
1013 }
1014
1015 var ok bool
1016 sessionId := string(hs.clientHello.sessionId)
1017 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
1018 return false
1019 }
Adam Langley95c29f32014-06-20 12:00:00 -07001020 }
1021
David Benjamin405da482016-08-08 17:25:07 -04001022 if !c.config.Bugs.AcceptAnySession {
1023 // Never resume a session for a different SSL version.
1024 if c.vers != hs.sessionState.vers {
1025 return false
Adam Langley95c29f32014-06-20 12:00:00 -07001026 }
David Benjamin405da482016-08-08 17:25:07 -04001027
1028 cipherSuiteOk := false
1029 // Check that the client is still offering the ciphersuite in the session.
1030 for _, id := range hs.clientHello.cipherSuites {
1031 if id == hs.sessionState.cipherSuite {
1032 cipherSuiteOk = true
1033 break
1034 }
1035 }
1036 if !cipherSuiteOk {
1037 return false
1038 }
Adam Langley95c29f32014-06-20 12:00:00 -07001039 }
1040
1041 // Check that we also support the ciphersuite from the session.
Nick Harper728eed82016-07-07 17:36:52 -07001042 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 -07001043 if hs.suite == nil {
1044 return false
1045 }
1046
1047 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
1048 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
1049 if needClientCerts && !sessionHasClientCerts {
1050 return false
1051 }
1052 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
1053 return false
1054 }
1055
1056 return true
1057}
1058
1059func (hs *serverHandshakeState) doResumeHandshake() error {
1060 c := hs.c
1061
1062 hs.hello.cipherSuite = hs.suite.id
David Benjaminece3de92015-03-16 18:02:20 -04001063 if c.config.Bugs.SendCipherSuite != 0 {
1064 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
1065 }
Adam Langley95c29f32014-06-20 12:00:00 -07001066 // We echo the client's session ID in the ServerHello to let it know
1067 // that we're doing a resumption.
1068 hs.hello.sessionId = hs.clientHello.sessionId
Nick Harperb3d51be2016-07-01 11:43:18 -04001069 hs.hello.extensions.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -07001070
David Benjamin80d1b352016-05-04 19:19:06 -04001071 if c.config.Bugs.SendSCTListOnResume != nil {
Nick Harperb3d51be2016-07-01 11:43:18 -04001072 hs.hello.extensions.sctList = c.config.Bugs.SendSCTListOnResume
David Benjamin80d1b352016-05-04 19:19:06 -04001073 }
1074
Adam Langley95c29f32014-06-20 12:00:00 -07001075 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -04001076 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -04001077 hs.writeClientHash(hs.clientHello.marshal())
1078 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001079
1080 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
1081
1082 if len(hs.sessionState.certificates) > 0 {
1083 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
1084 return err
1085 }
1086 }
1087
1088 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -07001089 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -07001090
1091 return nil
1092}
1093
1094func (hs *serverHandshakeState) doFullHandshake() error {
1095 config := hs.c.config
1096 c := hs.c
1097
David Benjamin48cae082014-10-27 01:06:24 -04001098 isPSK := hs.suite.flags&suitePSK != 0
1099 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001100 hs.hello.extensions.ocspStapling = true
Adam Langley95c29f32014-06-20 12:00:00 -07001101 }
1102
David Benjamin61f95272014-11-25 01:55:35 -05001103 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001104 hs.hello.extensions.sctList = hs.cert.SignedCertificateTimestampList
David Benjamin61f95272014-11-25 01:55:35 -05001105 }
1106
Nick Harperb3d51be2016-07-01 11:43:18 -04001107 hs.hello.extensions.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
Adam Langley95c29f32014-06-20 12:00:00 -07001108 hs.hello.cipherSuite = hs.suite.id
David Benjamin6095de82014-12-27 01:50:38 -05001109 if config.Bugs.SendCipherSuite != 0 {
1110 hs.hello.cipherSuite = config.Bugs.SendCipherSuite
1111 }
Nick Harperb3d51be2016-07-01 11:43:18 -04001112 c.extendedMasterSecret = hs.hello.extensions.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -07001113
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001114 // Generate a session ID if we're to save the session.
Nick Harperb3d51be2016-07-01 11:43:18 -04001115 if !hs.hello.extensions.ticketSupported && config.ServerSessionCache != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001116 hs.hello.sessionId = make([]byte, 32)
1117 if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
1118 c.sendAlert(alertInternalError)
1119 return errors.New("tls: short read from Rand: " + err.Error())
1120 }
1121 }
1122
Adam Langley95c29f32014-06-20 12:00:00 -07001123 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -04001124 hs.writeClientHash(hs.clientHello.marshal())
1125 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001126
1127 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
1128
David Benjamin48cae082014-10-27 01:06:24 -04001129 if !isPSK {
1130 certMsg := new(certificateMsg)
David Benjamin8923c0b2015-06-07 11:42:34 -04001131 if !config.Bugs.EmptyCertificateList {
1132 certMsg.certificates = hs.cert.Certificate
1133 }
David Benjamin48cae082014-10-27 01:06:24 -04001134 if !config.Bugs.UnauthenticatedECDH {
David Benjaminbcb2d912015-02-24 23:45:43 -05001135 certMsgBytes := certMsg.marshal()
David Benjaminbcb2d912015-02-24 23:45:43 -05001136 hs.writeServerHash(certMsgBytes)
1137 c.writeRecord(recordTypeHandshake, certMsgBytes)
David Benjamin48cae082014-10-27 01:06:24 -04001138 }
David Benjamin1c375dd2014-07-12 00:48:23 -04001139 }
Adam Langley95c29f32014-06-20 12:00:00 -07001140
Nick Harperb3d51be2016-07-01 11:43:18 -04001141 if hs.hello.extensions.ocspStapling && !c.config.Bugs.SkipCertificateStatus {
Adam Langley95c29f32014-06-20 12:00:00 -07001142 certStatus := new(certificateStatusMsg)
1143 certStatus.statusType = statusTypeOCSP
1144 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -04001145 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001146 c.writeRecord(recordTypeHandshake, certStatus.marshal())
1147 }
1148
1149 keyAgreement := hs.suite.ka(c.vers)
1150 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
1151 if err != nil {
1152 c.sendAlert(alertHandshakeFailure)
1153 return err
1154 }
Steven Valdez5440fe02016-07-18 12:40:30 -04001155 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
1156 c.curveID = ecdhe.curveID
1157 }
David Benjamin9c651c92014-07-12 13:27:45 -04001158 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -04001159 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001160 c.writeRecord(recordTypeHandshake, skx.marshal())
1161 }
1162
1163 if config.ClientAuth >= RequestClientCert {
1164 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -04001165 certReq := &certificateRequestMsg{
1166 certificateTypes: config.ClientCertificateTypes,
1167 }
1168 if certReq.certificateTypes == nil {
1169 certReq.certificateTypes = []byte{
1170 byte(CertTypeRSASign),
1171 byte(CertTypeECDSASign),
1172 }
Adam Langley95c29f32014-06-20 12:00:00 -07001173 }
1174 if c.vers >= VersionTLS12 {
Nick Harper60edffd2016-06-21 15:19:24 -07001175 certReq.hasSignatureAlgorithm = true
1176 if !config.Bugs.NoSignatureAlgorithms {
David Benjamin7a41d372016-07-09 11:21:54 -07001177 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin000800a2014-11-14 01:43:59 -05001178 }
Adam Langley95c29f32014-06-20 12:00:00 -07001179 }
1180
1181 // An empty list of certificateAuthorities signals to
1182 // the client that it may send any certificate in response
1183 // to our request. When we know the CAs we trust, then
1184 // we can send them down, so that the client can choose
1185 // an appropriate certificate to give to us.
1186 if config.ClientCAs != nil {
1187 certReq.certificateAuthorities = config.ClientCAs.Subjects()
1188 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001189 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001190 c.writeRecord(recordTypeHandshake, certReq.marshal())
1191 }
1192
1193 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001194 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001195 c.writeRecord(recordTypeHandshake, helloDone.marshal())
David Benjamin582ba042016-07-07 12:33:25 -07001196 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001197
1198 var pub crypto.PublicKey // public key for client auth, if any
1199
David Benjamin83f90402015-01-27 01:09:43 -05001200 if err := c.simulatePacketLoss(nil); err != nil {
1201 return err
1202 }
Adam Langley95c29f32014-06-20 12:00:00 -07001203 msg, err := c.readHandshake()
1204 if err != nil {
1205 return err
1206 }
1207
1208 var ok bool
1209 // If we requested a client certificate, then the client must send a
1210 // certificate message, even if it's empty.
1211 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -04001212 var certMsg *certificateMsg
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001213 var certificates [][]byte
1214 if certMsg, ok = msg.(*certificateMsg); ok {
1215 if c.vers == VersionSSL30 && len(certMsg.certificates) == 0 {
1216 return errors.New("tls: empty certificate message in SSL 3.0")
1217 }
1218
1219 hs.writeClientHash(certMsg.marshal())
1220 certificates = certMsg.certificates
1221 } else if c.vers != VersionSSL30 {
1222 // In TLS, the Certificate message is required. In SSL
1223 // 3.0, the peer skips it when sending no certificates.
Adam Langley95c29f32014-06-20 12:00:00 -07001224 c.sendAlert(alertUnexpectedMessage)
1225 return unexpectedMessageError(certMsg, msg)
1226 }
Adam Langley95c29f32014-06-20 12:00:00 -07001227
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001228 if len(certificates) == 0 {
Adam Langley95c29f32014-06-20 12:00:00 -07001229 // The client didn't actually send a certificate
1230 switch config.ClientAuth {
1231 case RequireAnyClientCert, RequireAndVerifyClientCert:
1232 c.sendAlert(alertBadCertificate)
1233 return errors.New("tls: client didn't provide a certificate")
1234 }
1235 }
1236
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001237 pub, err = hs.processCertsFromClient(certificates)
Adam Langley95c29f32014-06-20 12:00:00 -07001238 if err != nil {
1239 return err
1240 }
1241
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001242 if ok {
1243 msg, err = c.readHandshake()
1244 if err != nil {
1245 return err
1246 }
Adam Langley95c29f32014-06-20 12:00:00 -07001247 }
1248 }
1249
1250 // Get client key exchange
1251 ckx, ok := msg.(*clientKeyExchangeMsg)
1252 if !ok {
1253 c.sendAlert(alertUnexpectedMessage)
1254 return unexpectedMessageError(ckx, msg)
1255 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001256 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001257
David Benjamine098ec22014-08-27 23:13:20 -04001258 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
1259 if err != nil {
1260 c.sendAlert(alertHandshakeFailure)
1261 return err
1262 }
Adam Langley75712922014-10-10 16:23:43 -07001263 if c.extendedMasterSecret {
1264 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1265 } else {
1266 if c.config.Bugs.RequireExtendedMasterSecret {
1267 return errors.New("tls: extended master secret required but not supported by peer")
1268 }
1269 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
1270 }
David Benjamine098ec22014-08-27 23:13:20 -04001271
Adam Langley95c29f32014-06-20 12:00:00 -07001272 // If we received a client cert in response to our certificate request message,
1273 // the client will send us a certificateVerifyMsg immediately after the
1274 // clientKeyExchangeMsg. This message is a digest of all preceding
1275 // handshake-layer messages that is signed using the private key corresponding
1276 // to the client's certificate. This allows us to verify that the client is in
1277 // possession of the private key of the certificate.
1278 if len(c.peerCertificates) > 0 {
1279 msg, err = c.readHandshake()
1280 if err != nil {
1281 return err
1282 }
1283 certVerify, ok := msg.(*certificateVerifyMsg)
1284 if !ok {
1285 c.sendAlert(alertUnexpectedMessage)
1286 return unexpectedMessageError(certVerify, msg)
1287 }
1288
David Benjaminde620d92014-07-18 15:03:41 -04001289 // Determine the signature type.
Nick Harper60edffd2016-06-21 15:19:24 -07001290 var sigAlg signatureAlgorithm
1291 if certVerify.hasSignatureAlgorithm {
1292 sigAlg = certVerify.signatureAlgorithm
Nick Harper60edffd2016-06-21 15:19:24 -07001293 c.peerSignatureAlgorithm = sigAlg
David Benjaminde620d92014-07-18 15:03:41 -04001294 }
1295
Nick Harper60edffd2016-06-21 15:19:24 -07001296 if c.vers > VersionSSL30 {
David Benjamin1fb125c2016-07-08 18:52:12 -07001297 err = verifyMessage(c.vers, pub, c.config, sigAlg, hs.finishedHash.buffer, certVerify.signature)
Nick Harper60edffd2016-06-21 15:19:24 -07001298 } else {
1299 // SSL 3.0's client certificate construction is
1300 // incompatible with signatureAlgorithm.
1301 rsaPub, ok := pub.(*rsa.PublicKey)
1302 if !ok {
1303 err = errors.New("unsupported key type for client certificate")
1304 } else {
1305 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
1306 err = rsa.VerifyPKCS1v15(rsaPub, crypto.MD5SHA1, digest, certVerify.signature)
David Benjaminde620d92014-07-18 15:03:41 -04001307 }
Adam Langley95c29f32014-06-20 12:00:00 -07001308 }
1309 if err != nil {
1310 c.sendAlert(alertBadCertificate)
1311 return errors.New("could not validate signature of connection nonces: " + err.Error())
1312 }
1313
David Benjamin83c0bc92014-08-04 01:23:53 -04001314 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001315 }
1316
David Benjamine098ec22014-08-27 23:13:20 -04001317 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001318
1319 return nil
1320}
1321
1322func (hs *serverHandshakeState) establishKeys() error {
1323 c := hs.c
1324
1325 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001326 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 -07001327
1328 var clientCipher, serverCipher interface{}
1329 var clientHash, serverHash macFunction
1330
1331 if hs.suite.aead == nil {
1332 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
1333 clientHash = hs.suite.mac(c.vers, clientMAC)
1334 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
1335 serverHash = hs.suite.mac(c.vers, serverMAC)
1336 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001337 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1338 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001339 }
1340
1341 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
1342 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
1343
1344 return nil
1345}
1346
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001347func (hs *serverHandshakeState) readFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001348 c := hs.c
1349
1350 c.readRecord(recordTypeChangeCipherSpec)
1351 if err := c.in.error(); err != nil {
1352 return err
1353 }
1354
Nick Harperb3d51be2016-07-01 11:43:18 -04001355 if hs.hello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001356 msg, err := c.readHandshake()
1357 if err != nil {
1358 return err
1359 }
1360 nextProto, ok := msg.(*nextProtoMsg)
1361 if !ok {
1362 c.sendAlert(alertUnexpectedMessage)
1363 return unexpectedMessageError(nextProto, msg)
1364 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001365 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001366 c.clientProtocol = nextProto.proto
1367 }
1368
Nick Harperb3d51be2016-07-01 11:43:18 -04001369 if hs.hello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001370 msg, err := c.readHandshake()
1371 if err != nil {
1372 return err
1373 }
David Benjamin24599a82016-06-30 18:56:53 -04001374 channelIDMsg, ok := msg.(*channelIDMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001375 if !ok {
1376 c.sendAlert(alertUnexpectedMessage)
David Benjamin24599a82016-06-30 18:56:53 -04001377 return unexpectedMessageError(channelIDMsg, msg)
David Benjamind30a9902014-08-24 01:44:23 -04001378 }
David Benjamin24599a82016-06-30 18:56:53 -04001379 x := new(big.Int).SetBytes(channelIDMsg.channelID[0:32])
1380 y := new(big.Int).SetBytes(channelIDMsg.channelID[32:64])
1381 r := new(big.Int).SetBytes(channelIDMsg.channelID[64:96])
1382 s := new(big.Int).SetBytes(channelIDMsg.channelID[96:128])
David Benjamind30a9902014-08-24 01:44:23 -04001383 if !elliptic.P256().IsOnCurve(x, y) {
1384 return errors.New("tls: invalid channel ID public key")
1385 }
1386 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
1387 var resumeHash []byte
1388 if isResume {
1389 resumeHash = hs.sessionState.handshakeHash
1390 }
1391 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
1392 return errors.New("tls: invalid channel ID signature")
1393 }
1394 c.channelID = channelID
1395
David Benjamin24599a82016-06-30 18:56:53 -04001396 hs.writeClientHash(channelIDMsg.marshal())
David Benjamind30a9902014-08-24 01:44:23 -04001397 }
1398
Adam Langley95c29f32014-06-20 12:00:00 -07001399 msg, err := c.readHandshake()
1400 if err != nil {
1401 return err
1402 }
1403 clientFinished, ok := msg.(*finishedMsg)
1404 if !ok {
1405 c.sendAlert(alertUnexpectedMessage)
1406 return unexpectedMessageError(clientFinished, msg)
1407 }
1408
1409 verify := hs.finishedHash.clientSum(hs.masterSecret)
1410 if len(verify) != len(clientFinished.verifyData) ||
1411 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
1412 c.sendAlert(alertHandshakeFailure)
1413 return errors.New("tls: client's Finished message is incorrect")
1414 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001415 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001416 copy(out, clientFinished.verifyData)
Adam Langley95c29f32014-06-20 12:00:00 -07001417
David Benjamin83c0bc92014-08-04 01:23:53 -04001418 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001419 return nil
1420}
1421
1422func (hs *serverHandshakeState) sendSessionTicket() error {
Adam Langley95c29f32014-06-20 12:00:00 -07001423 c := hs.c
Adam Langley95c29f32014-06-20 12:00:00 -07001424 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -04001425 vers: c.vers,
1426 cipherSuite: hs.suite.id,
1427 masterSecret: hs.masterSecret,
1428 certificates: hs.certsFromClient,
1429 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -07001430 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001431
Nick Harperb3d51be2016-07-01 11:43:18 -04001432 if !hs.hello.extensions.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001433 if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
1434 c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
1435 }
1436 return nil
1437 }
1438
1439 m := new(newSessionTicketMsg)
1440
David Benjamindd6fed92015-10-23 17:41:12 -04001441 if !c.config.Bugs.SendEmptySessionTicket {
1442 var err error
1443 m.ticket, err = c.encryptTicket(&state)
1444 if err != nil {
1445 return err
1446 }
Adam Langley95c29f32014-06-20 12:00:00 -07001447 }
Adam Langley95c29f32014-06-20 12:00:00 -07001448
David Benjamin83c0bc92014-08-04 01:23:53 -04001449 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001450 c.writeRecord(recordTypeHandshake, m.marshal())
1451
1452 return nil
1453}
1454
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001455func (hs *serverHandshakeState) sendFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001456 c := hs.c
1457
David Benjamin86271ee2014-07-21 16:14:03 -04001458 finished := new(finishedMsg)
1459 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001460 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001461 if c.config.Bugs.BadFinished {
1462 finished.verifyData[0]++
1463 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001464 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001465 hs.finishedBytes = finished.marshal()
1466 hs.writeServerHash(hs.finishedBytes)
1467 postCCSBytes := hs.finishedBytes
David Benjamin86271ee2014-07-21 16:14:03 -04001468
1469 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
1470 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
1471 postCCSBytes = postCCSBytes[5:]
David Benjamin61672812016-07-14 23:10:43 -04001472 } else if c.config.Bugs.SendUnencryptedFinished {
1473 c.writeRecord(recordTypeHandshake, postCCSBytes)
1474 postCCSBytes = nil
David Benjamin86271ee2014-07-21 16:14:03 -04001475 }
David Benjamin582ba042016-07-07 12:33:25 -07001476 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001477
David Benjamina0e52232014-07-19 17:39:58 -04001478 if !c.config.Bugs.SkipChangeCipherSpec {
David Benjamin8411b242015-11-26 12:07:28 -05001479 ccs := []byte{1}
1480 if c.config.Bugs.BadChangeCipherSpec != nil {
1481 ccs = c.config.Bugs.BadChangeCipherSpec
1482 }
1483 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamina0e52232014-07-19 17:39:58 -04001484 }
Adam Langley95c29f32014-06-20 12:00:00 -07001485
David Benjamin4189bd92015-01-25 23:52:39 -05001486 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1487 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1488 }
David Benjamindc3da932015-03-12 15:09:02 -04001489 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1490 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1491 return errors.New("tls: simulating post-CCS alert")
1492 }
David Benjamin4189bd92015-01-25 23:52:39 -05001493
David Benjamin61672812016-07-14 23:10:43 -04001494 if !c.config.Bugs.SkipFinished && len(postCCSBytes) > 0 {
David Benjaminb80168e2015-02-08 18:30:14 -05001495 c.writeRecord(recordTypeHandshake, postCCSBytes)
David Benjamin02edcd02016-07-27 17:40:37 -04001496 if c.config.Bugs.SendExtraFinished {
1497 c.writeRecord(recordTypeHandshake, finished.marshal())
1498 }
1499
David Benjamin12d2c482016-07-24 10:56:51 -04001500 if !c.config.Bugs.PackHelloRequestWithFinished {
1501 // Defer flushing until renegotiation.
1502 c.flushHandshake()
1503 }
David Benjaminb3774b92015-01-31 17:16:01 -05001504 }
Adam Langley95c29f32014-06-20 12:00:00 -07001505
David Benjaminc565ebb2015-04-03 04:06:36 -04001506 c.cipherSuite = hs.suite
Adam Langley95c29f32014-06-20 12:00:00 -07001507
1508 return nil
1509}
1510
1511// processCertsFromClient takes a chain of client certificates either from a
1512// Certificates message or from a sessionState and verifies them. It returns
1513// the public key of the leaf certificate.
1514func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
1515 c := hs.c
1516
1517 hs.certsFromClient = certificates
1518 certs := make([]*x509.Certificate, len(certificates))
1519 var err error
1520 for i, asn1Data := range certificates {
1521 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
1522 c.sendAlert(alertBadCertificate)
1523 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
1524 }
1525 }
1526
1527 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
1528 opts := x509.VerifyOptions{
1529 Roots: c.config.ClientCAs,
1530 CurrentTime: c.config.time(),
1531 Intermediates: x509.NewCertPool(),
1532 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
1533 }
1534
1535 for _, cert := range certs[1:] {
1536 opts.Intermediates.AddCert(cert)
1537 }
1538
1539 chains, err := certs[0].Verify(opts)
1540 if err != nil {
1541 c.sendAlert(alertBadCertificate)
1542 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
1543 }
1544
1545 ok := false
1546 for _, ku := range certs[0].ExtKeyUsage {
1547 if ku == x509.ExtKeyUsageClientAuth {
1548 ok = true
1549 break
1550 }
1551 }
1552 if !ok {
1553 c.sendAlert(alertHandshakeFailure)
1554 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
1555 }
1556
1557 c.verifiedChains = chains
1558 }
1559
1560 if len(certs) > 0 {
1561 var pub crypto.PublicKey
1562 switch key := certs[0].PublicKey.(type) {
1563 case *ecdsa.PublicKey, *rsa.PublicKey:
1564 pub = key
1565 default:
1566 c.sendAlert(alertUnsupportedCertificate)
1567 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
1568 }
1569 c.peerCertificates = certs
1570 return pub, nil
1571 }
1572
1573 return nil, nil
1574}
1575
David Benjamin83c0bc92014-08-04 01:23:53 -04001576func (hs *serverHandshakeState) writeServerHash(msg []byte) {
1577 // writeServerHash is called before writeRecord.
1578 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1579}
1580
1581func (hs *serverHandshakeState) writeClientHash(msg []byte) {
1582 // writeClientHash is called after readHandshake.
1583 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1584}
1585
1586func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
1587 if hs.c.isDTLS {
1588 // This is somewhat hacky. DTLS hashes a slightly different format.
1589 // First, the TLS header.
1590 hs.finishedHash.Write(msg[:4])
1591 // Then the sequence number and reassembled fragment offset (always 0).
1592 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1593 // Then the reassembled fragment (always equal to the message length).
1594 hs.finishedHash.Write(msg[1:4])
1595 // And then the message body.
1596 hs.finishedHash.Write(msg[4:])
1597 } else {
1598 hs.finishedHash.Write(msg)
1599 }
1600}
1601
Adam Langley95c29f32014-06-20 12:00:00 -07001602// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
1603// is acceptable to use.
Nick Harper728eed82016-07-07 17:36:52 -07001604func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk, pskOk bool) *cipherSuite {
Adam Langley95c29f32014-06-20 12:00:00 -07001605 for _, supported := range supportedCipherSuites {
1606 if id == supported {
1607 var candidate *cipherSuite
1608
1609 for _, s := range cipherSuites {
1610 if s.id == id {
1611 candidate = s
1612 break
1613 }
1614 }
1615 if candidate == nil {
1616 continue
1617 }
1618 // Don't select a ciphersuite which we can't
1619 // support for this client.
David Benjamin0407e762016-06-17 16:41:18 -04001620 if !c.config.Bugs.EnableAllCiphers {
Nick Harper728eed82016-07-07 17:36:52 -07001621 if (candidate.flags&suitePSK != 0) && !pskOk {
1622 continue
1623 }
David Benjamin0407e762016-06-17 16:41:18 -04001624 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
1625 continue
1626 }
1627 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
1628 continue
1629 }
1630 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
1631 continue
1632 }
Nick Harper728eed82016-07-07 17:36:52 -07001633 if version >= VersionTLS13 && candidate.flags&suiteTLS13 == 0 {
1634 continue
1635 }
David Benjamin0407e762016-06-17 16:41:18 -04001636 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
1637 continue
1638 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001639 }
Adam Langley95c29f32014-06-20 12:00:00 -07001640 return candidate
1641 }
1642 }
1643
1644 return nil
1645}
David Benjaminf93995b2015-11-05 18:23:20 -05001646
1647func isTLS12Cipher(id uint16) bool {
1648 for _, cipher := range cipherSuites {
1649 if cipher.id != id {
1650 continue
1651 }
1652 return cipher.flags&suiteTLS12 != 0
1653 }
1654 // Unknown cipher.
1655 return false
1656}