blob: 64e2a71e0fe24e8577031371826ee28a15e3135f [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
David Benjamine73c7f42016-08-17 00:29:33 -0400433 if config.Bugs.ExpectMissingKeyShare && selectedKeyShare != nil {
434 return errors.New("tls: expected missing key share")
435 }
436
Steven Valdez5440fe02016-07-18 12:40:30 -0400437 sendHelloRetryRequest := selectedKeyShare == nil
438 if config.Bugs.UnnecessaryHelloRetryRequest {
439 sendHelloRetryRequest = true
440 }
441 if config.Bugs.SkipHelloRetryRequest {
442 sendHelloRetryRequest = false
443 }
444 if sendHelloRetryRequest {
445 firstTime := true
446 ResendHelloRetryRequest:
Nick Harperdcfbc672016-07-16 17:47:31 +0200447 // Send HelloRetryRequest.
448 helloRetryRequestMsg := helloRetryRequestMsg{
449 vers: c.vers,
450 cipherSuite: hs.hello.cipherSuite,
451 selectedGroup: selectedCurve,
452 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400453 if config.Bugs.SendHelloRetryRequestCurve != 0 {
454 helloRetryRequestMsg.selectedGroup = config.Bugs.SendHelloRetryRequestCurve
455 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200456 hs.writeServerHash(helloRetryRequestMsg.marshal())
457 c.writeRecord(recordTypeHandshake, helloRetryRequestMsg.marshal())
David Benjamine73c7f42016-08-17 00:29:33 -0400458 c.flushHandshake()
Nick Harperdcfbc672016-07-16 17:47:31 +0200459
460 // Read new ClientHello.
461 newMsg, err := c.readHandshake()
462 if err != nil {
463 return err
464 }
465 newClientHello, ok := newMsg.(*clientHelloMsg)
466 if !ok {
467 c.sendAlert(alertUnexpectedMessage)
468 return unexpectedMessageError(newClientHello, newMsg)
469 }
470 hs.writeClientHash(newClientHello.marshal())
471
472 // Check that the new ClientHello matches the old ClientHello, except for
473 // the addition of the new KeyShareEntry at the end of the list, and
474 // removing the EarlyDataIndication extension (if present).
475 newKeyShares := newClientHello.keyShares
476 if len(newKeyShares) == 0 || newKeyShares[len(newKeyShares)-1].group != selectedCurve {
477 return errors.New("tls: KeyShare from HelloRetryRequest not present in new ClientHello")
478 }
479 oldClientHelloCopy := *hs.clientHello
480 oldClientHelloCopy.raw = nil
481 oldClientHelloCopy.hasEarlyData = false
482 oldClientHelloCopy.earlyDataContext = nil
483 newClientHelloCopy := *newClientHello
484 newClientHelloCopy.raw = nil
485 newClientHelloCopy.keyShares = newKeyShares[:len(newKeyShares)-1]
486 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
487 return errors.New("tls: new ClientHello does not match")
488 }
489
Steven Valdez5440fe02016-07-18 12:40:30 -0400490 if firstTime && config.Bugs.SecondHelloRetryRequest {
491 firstTime = false
492 goto ResendHelloRetryRequest
493 }
494
Nick Harperdcfbc672016-07-16 17:47:31 +0200495 selectedKeyShare = &newKeyShares[len(newKeyShares)-1]
Nick Harper728eed82016-07-07 17:36:52 -0700496 }
497
498 // Once a curve has been selected and a key share identified,
499 // the server needs to generate a public value and send it in
500 // the ServerHello.
Steven Valdez5440fe02016-07-18 12:40:30 -0400501 curve, ok := curveForCurveID(selectedCurve)
Nick Harper728eed82016-07-07 17:36:52 -0700502 if !ok {
503 panic("tls: server failed to look up curve ID")
504 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400505 c.curveID = selectedCurve
506
507 var peerKey []byte
508 if config.Bugs.SkipHelloRetryRequest {
509 // If skipping HelloRetryRequest, use a random key to
510 // avoid crashing.
511 curve2, _ := curveForCurveID(selectedCurve)
512 var err error
513 peerKey, err = curve2.offer(config.rand())
514 if err != nil {
515 return err
516 }
517 } else {
518 peerKey = selectedKeyShare.keyExchange
519 }
520
Nick Harper728eed82016-07-07 17:36:52 -0700521 var publicKey []byte
522 var err error
Steven Valdez5440fe02016-07-18 12:40:30 -0400523 publicKey, ecdheSecret, err = curve.accept(config.rand(), peerKey)
Nick Harper728eed82016-07-07 17:36:52 -0700524 if err != nil {
525 c.sendAlert(alertHandshakeFailure)
526 return err
527 }
528 hs.hello.hasKeyShare = true
Steven Valdez0ee2e112016-07-15 06:51:15 -0400529
Steven Valdez5440fe02016-07-18 12:40:30 -0400530 curveID := selectedCurve
Steven Valdez0ee2e112016-07-15 06:51:15 -0400531 if c.config.Bugs.SendCurve != 0 {
532 curveID = config.Bugs.SendCurve
533 }
534 if c.config.Bugs.InvalidECDHPoint {
535 publicKey[0] ^= 0xff
536 }
537
Nick Harper728eed82016-07-07 17:36:52 -0700538 hs.hello.keyShare = keyShareEntry{
Steven Valdez0ee2e112016-07-15 06:51:15 -0400539 group: curveID,
Nick Harper728eed82016-07-07 17:36:52 -0700540 keyExchange: publicKey,
541 }
Steven Valdez143e8b32016-07-11 13:19:03 -0400542
543 if config.Bugs.EncryptedExtensionsWithKeyShare {
544 encryptedExtensions.extensions.hasKeyShare = true
545 encryptedExtensions.extensions.keyShare = keyShareEntry{
546 group: curveID,
547 keyExchange: publicKey,
548 }
549 }
Nick Harper728eed82016-07-07 17:36:52 -0700550 } else {
551 ecdheSecret = hs.finishedHash.zeroSecret()
552 }
553
554 // Send unencrypted ServerHello.
555 hs.writeServerHash(hs.hello.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400556 if config.Bugs.PartialEncryptedExtensionsWithServerHello {
557 helloBytes := hs.hello.marshal()
558 toWrite := make([]byte, 0, len(helloBytes)+1)
559 toWrite = append(toWrite, helloBytes...)
560 toWrite = append(toWrite, typeEncryptedExtensions)
561 c.writeRecord(recordTypeHandshake, toWrite)
562 } else {
563 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
564 }
Nick Harper728eed82016-07-07 17:36:52 -0700565 c.flushHandshake()
566
567 // Compute the handshake secret.
568 handshakeSecret := hs.finishedHash.extractKey(earlySecret, ecdheSecret)
569
570 // Switch to handshake traffic keys.
571 handshakeTrafficSecret := hs.finishedHash.deriveSecret(handshakeSecret, handshakeTrafficLabel)
David Benjamin21c00282016-07-18 21:56:23 +0200572 c.out.useTrafficSecret(c.vers, hs.suite, handshakeTrafficSecret, handshakePhase, serverWrite)
573 c.in.useTrafficSecret(c.vers, hs.suite, handshakeTrafficSecret, handshakePhase, clientWrite)
Nick Harper728eed82016-07-07 17:36:52 -0700574
Nick Harper0b3625b2016-07-25 16:16:28 -0700575 if hs.suite.flags&suitePSK == 0 {
David Benjamin615119a2016-07-06 19:22:55 -0700576 if hs.clientHello.ocspStapling {
577 encryptedExtensions.extensions.ocspResponse = hs.cert.OCSPStaple
578 }
579 if hs.clientHello.sctListSupported {
580 encryptedExtensions.extensions.sctList = hs.cert.SignedCertificateTimestampList
581 }
582 }
583
Nick Harper728eed82016-07-07 17:36:52 -0700584 // Send EncryptedExtensions.
585 hs.writeServerHash(encryptedExtensions.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400586 if config.Bugs.PartialEncryptedExtensionsWithServerHello {
587 // The first byte has already been sent.
588 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()[1:])
589 } else {
590 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal())
591 }
Nick Harper728eed82016-07-07 17:36:52 -0700592
593 if hs.suite.flags&suitePSK == 0 {
594 if config.ClientAuth >= RequestClientCert {
David Benjamin8d343b42016-07-09 14:26:01 -0700595 // Request a client certificate
596 certReq := &certificateRequestMsg{
597 hasSignatureAlgorithm: true,
598 hasRequestContext: true,
599 }
600 if !config.Bugs.NoSignatureAlgorithms {
David Benjaminf74ec792016-07-13 21:18:49 -0400601 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin8d343b42016-07-09 14:26:01 -0700602 }
603
604 // An empty list of certificateAuthorities signals to
605 // the client that it may send any certificate in response
606 // to our request. When we know the CAs we trust, then
607 // we can send them down, so that the client can choose
608 // an appropriate certificate to give to us.
609 if config.ClientCAs != nil {
610 certReq.certificateAuthorities = config.ClientCAs.Subjects()
611 }
612 hs.writeServerHash(certReq.marshal())
613 c.writeRecord(recordTypeHandshake, certReq.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700614 }
615
616 certMsg := &certificateMsg{
617 hasRequestContext: true,
618 }
619 if !config.Bugs.EmptyCertificateList {
620 certMsg.certificates = hs.cert.Certificate
621 }
David Benjamin1edae6b2016-07-13 16:58:23 -0400622 certMsgBytes := certMsg.marshal()
David Benjamin1edae6b2016-07-13 16:58:23 -0400623 hs.writeServerHash(certMsgBytes)
624 c.writeRecord(recordTypeHandshake, certMsgBytes)
Nick Harper728eed82016-07-07 17:36:52 -0700625
626 certVerify := &certificateVerifyMsg{
627 hasSignatureAlgorithm: true,
628 }
629
630 // Determine the hash to sign.
631 privKey := hs.cert.PrivateKey
632
633 var err error
634 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, config, hs.clientHello.signatureAlgorithms)
635 if err != nil {
636 c.sendAlert(alertInternalError)
637 return err
638 }
639
640 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
641 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
642 if err != nil {
643 c.sendAlert(alertInternalError)
644 return err
645 }
646
Steven Valdez0ee2e112016-07-15 06:51:15 -0400647 if config.Bugs.SendSignatureAlgorithm != 0 {
648 certVerify.signatureAlgorithm = config.Bugs.SendSignatureAlgorithm
649 }
650
Nick Harper728eed82016-07-07 17:36:52 -0700651 hs.writeServerHash(certVerify.marshal())
652 c.writeRecord(recordTypeHandshake, certVerify.marshal())
Nick Harper0b3625b2016-07-25 16:16:28 -0700653 } else {
654 // Pick up certificates from the session instead.
655 // hs.sessionState may be nil if config.Bugs.EnableAllCiphers is
656 // true.
657 if hs.sessionState != nil && len(hs.sessionState.certificates) > 0 {
658 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
659 return err
660 }
661 }
Nick Harper728eed82016-07-07 17:36:52 -0700662 }
663
664 finished := new(finishedMsg)
665 finished.verifyData = hs.finishedHash.serverSum(handshakeTrafficSecret)
666 if config.Bugs.BadFinished {
667 finished.verifyData[0]++
668 }
669 hs.writeServerHash(finished.marshal())
670 c.writeRecord(recordTypeHandshake, finished.marshal())
David Benjamin02edcd02016-07-27 17:40:37 -0400671 if c.config.Bugs.SendExtraFinished {
672 c.writeRecord(recordTypeHandshake, finished.marshal())
673 }
Nick Harper728eed82016-07-07 17:36:52 -0700674 c.flushHandshake()
675
676 // The various secrets do not incorporate the client's final leg, so
677 // derive them now before updating the handshake context.
678 masterSecret := hs.finishedHash.extractKey(handshakeSecret, hs.finishedHash.zeroSecret())
679 trafficSecret := hs.finishedHash.deriveSecret(masterSecret, applicationTrafficLabel)
680
David Benjamin2aad4062016-07-14 23:15:40 -0400681 // Switch to application data keys on write. In particular, any alerts
682 // from the client certificate are sent over these keys.
David Benjamin21c00282016-07-18 21:56:23 +0200683 c.out.useTrafficSecret(c.vers, hs.suite, trafficSecret, applicationPhase, serverWrite)
David Benjamin2aad4062016-07-14 23:15:40 -0400684
Nick Harper728eed82016-07-07 17:36:52 -0700685 // If we requested a client certificate, then the client must send a
686 // certificate message, even if it's empty.
687 if config.ClientAuth >= RequestClientCert {
David Benjamin8d343b42016-07-09 14:26:01 -0700688 msg, err := c.readHandshake()
689 if err != nil {
690 return err
691 }
692
693 certMsg, ok := msg.(*certificateMsg)
694 if !ok {
695 c.sendAlert(alertUnexpectedMessage)
696 return unexpectedMessageError(certMsg, msg)
697 }
698 hs.writeClientHash(certMsg.marshal())
699
700 if len(certMsg.certificates) == 0 {
701 // The client didn't actually send a certificate
702 switch config.ClientAuth {
703 case RequireAnyClientCert, RequireAndVerifyClientCert:
704 c.sendAlert(alertBadCertificate)
705 return errors.New("tls: client didn't provide a certificate")
706 }
707 }
708
709 pub, err := hs.processCertsFromClient(certMsg.certificates)
710 if err != nil {
711 return err
712 }
713
714 if len(c.peerCertificates) > 0 {
715 msg, err = c.readHandshake()
716 if err != nil {
717 return err
718 }
719
720 certVerify, ok := msg.(*certificateVerifyMsg)
721 if !ok {
722 c.sendAlert(alertUnexpectedMessage)
723 return unexpectedMessageError(certVerify, msg)
724 }
725
David Benjaminf74ec792016-07-13 21:18:49 -0400726 c.peerSignatureAlgorithm = certVerify.signatureAlgorithm
David Benjamin8d343b42016-07-09 14:26:01 -0700727 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
728 if err := verifyMessage(c.vers, pub, config, certVerify.signatureAlgorithm, input, certVerify.signature); err != nil {
729 c.sendAlert(alertBadCertificate)
730 return err
731 }
732 hs.writeClientHash(certVerify.marshal())
733 }
Nick Harper728eed82016-07-07 17:36:52 -0700734 }
735
736 // Read the client Finished message.
737 msg, err := c.readHandshake()
738 if err != nil {
739 return err
740 }
741 clientFinished, ok := msg.(*finishedMsg)
742 if !ok {
743 c.sendAlert(alertUnexpectedMessage)
744 return unexpectedMessageError(clientFinished, msg)
745 }
746
747 verify := hs.finishedHash.clientSum(handshakeTrafficSecret)
748 if len(verify) != len(clientFinished.verifyData) ||
749 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
750 c.sendAlert(alertHandshakeFailure)
751 return errors.New("tls: client's Finished message was incorrect")
752 }
David Benjamin97a0a082016-07-13 17:57:35 -0400753 hs.writeClientHash(clientFinished.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700754
David Benjamin2aad4062016-07-14 23:15:40 -0400755 // Switch to application data keys on read.
David Benjamin21c00282016-07-18 21:56:23 +0200756 c.in.useTrafficSecret(c.vers, hs.suite, trafficSecret, applicationPhase, clientWrite)
Nick Harper728eed82016-07-07 17:36:52 -0700757
Nick Harper728eed82016-07-07 17:36:52 -0700758 c.cipherSuite = hs.suite
David Benjamin97a0a082016-07-13 17:57:35 -0400759 c.exporterSecret = hs.finishedHash.deriveSecret(masterSecret, exporterLabel)
David Benjamin58104882016-07-18 01:25:41 +0200760 c.resumptionSecret = hs.finishedHash.deriveSecret(masterSecret, resumptionLabel)
761
762 // TODO(davidben): Allow configuring the number of tickets sent for
763 // testing.
764 if !c.config.SessionTicketsDisabled {
765 ticketCount := 2
766 for i := 0; i < ticketCount; i++ {
767 c.SendNewSessionTicket()
768 }
769 }
Nick Harper728eed82016-07-07 17:36:52 -0700770 return nil
771}
772
David Benjaminf25dda92016-07-04 10:05:26 -0700773// processClientHello processes the ClientHello message from the client and
774// decides whether we will perform session resumption.
775func (hs *serverHandshakeState) processClientHello() (isResume bool, err error) {
776 config := hs.c.config
777 c := hs.c
778
779 hs.hello = &serverHelloMsg{
780 isDTLS: c.isDTLS,
781 vers: c.vers,
782 compressionMethod: compressionNone,
783 }
784
Steven Valdez5440fe02016-07-18 12:40:30 -0400785 if config.Bugs.SendServerHelloVersion != 0 {
786 hs.hello.vers = config.Bugs.SendServerHelloVersion
787 }
788
David Benjaminf25dda92016-07-04 10:05:26 -0700789 hs.hello.random = make([]byte, 32)
790 _, err = io.ReadFull(config.rand(), hs.hello.random)
791 if err != nil {
792 c.sendAlert(alertInternalError)
793 return false, err
794 }
David Benjamin1f61f0d2016-07-10 12:20:35 -0400795 // Signal downgrades in the server random, per draft-ietf-tls-tls13-14,
796 // section 6.3.1.2.
Nick Harper85f20c22016-07-04 10:11:59 -0700797 if c.vers <= VersionTLS12 && config.maxVersion(c.isDTLS) >= VersionTLS13 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400798 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS13)
Nick Harper85f20c22016-07-04 10:11:59 -0700799 }
800 if c.vers <= VersionTLS11 && config.maxVersion(c.isDTLS) == VersionTLS12 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400801 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS12)
Nick Harper85f20c22016-07-04 10:11:59 -0700802 }
David Benjaminf25dda92016-07-04 10:05:26 -0700803
804 foundCompression := false
805 // We only support null compression, so check that the client offered it.
806 for _, compression := range hs.clientHello.compressionMethods {
807 if compression == compressionNone {
808 foundCompression = true
809 break
810 }
811 }
812
813 if !foundCompression {
814 c.sendAlert(alertHandshakeFailure)
815 return false, errors.New("tls: client does not support uncompressed connections")
816 }
David Benjamin7d79f832016-07-04 09:20:45 -0700817
818 if err := hs.processClientExtensions(&hs.hello.extensions); err != nil {
819 return false, err
Adam Langley09505632015-07-30 18:10:13 -0700820 }
Adam Langley95c29f32014-06-20 12:00:00 -0700821
822 supportedCurve := false
823 preferredCurves := config.curvePreferences()
824Curves:
825 for _, curve := range hs.clientHello.supportedCurves {
826 for _, supported := range preferredCurves {
827 if supported == curve {
828 supportedCurve = true
829 break Curves
830 }
831 }
832 }
833
834 supportedPointFormat := false
835 for _, pointFormat := range hs.clientHello.supportedPoints {
836 if pointFormat == pointFormatUncompressed {
837 supportedPointFormat = true
838 break
839 }
840 }
841 hs.ellipticOk = supportedCurve && supportedPointFormat
842
Adam Langley95c29f32014-06-20 12:00:00 -0700843 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
844
David Benjamin4b27d9f2015-05-12 22:42:52 -0400845 // For test purposes, check that the peer never offers a session when
846 // renegotiating.
847 if c.cipherSuite != nil && len(hs.clientHello.sessionId) > 0 && c.config.Bugs.FailIfResumeOnRenego {
848 return false, errors.New("tls: offered resumption on renegotiation")
849 }
850
David Benjamindd6fed92015-10-23 17:41:12 -0400851 if c.config.Bugs.FailIfSessionOffered && (len(hs.clientHello.sessionTicket) > 0 || len(hs.clientHello.sessionId) > 0) {
852 return false, errors.New("tls: client offered a session ticket or ID")
853 }
854
Adam Langley95c29f32014-06-20 12:00:00 -0700855 if hs.checkForResumption() {
856 return true, nil
857 }
858
Adam Langley95c29f32014-06-20 12:00:00 -0700859 var preferenceList, supportedList []uint16
860 if c.config.PreferServerCipherSuites {
861 preferenceList = c.config.cipherSuites()
862 supportedList = hs.clientHello.cipherSuites
863 } else {
864 preferenceList = hs.clientHello.cipherSuites
865 supportedList = c.config.cipherSuites()
866 }
867
868 for _, id := range preferenceList {
Nick Harper728eed82016-07-07 17:36:52 -0700869 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk, true); hs.suite != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700870 break
871 }
872 }
873
874 if hs.suite == nil {
875 c.sendAlert(alertHandshakeFailure)
876 return false, errors.New("tls: no cipher suite supported by both client and server")
877 }
878
879 return false, nil
880}
881
David Benjamin7d79f832016-07-04 09:20:45 -0700882// processClientExtensions processes all ClientHello extensions not directly
883// related to cipher suite negotiation and writes responses in serverExtensions.
884func (hs *serverHandshakeState) processClientExtensions(serverExtensions *serverExtensions) error {
885 config := hs.c.config
886 c := hs.c
887
David Benjamin8d315d72016-07-18 01:03:18 +0200888 if c.vers < VersionTLS13 || config.Bugs.NegotiateRenegotiationInfoAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700889 if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) {
890 c.sendAlert(alertHandshakeFailure)
891 return errors.New("tls: renegotiation mismatch")
David Benjamin7d79f832016-07-04 09:20:45 -0700892 }
David Benjamin7d79f832016-07-04 09:20:45 -0700893
Nick Harper728eed82016-07-07 17:36:52 -0700894 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
895 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.clientVerify...)
896 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.serverVerify...)
897 if c.config.Bugs.BadRenegotiationInfo {
898 serverExtensions.secureRenegotiation[0] ^= 0x80
899 }
900 } else {
901 serverExtensions.secureRenegotiation = hs.clientHello.secureRenegotiation
902 }
903
904 if c.noRenegotiationInfo() {
905 serverExtensions.secureRenegotiation = nil
906 }
David Benjamin7d79f832016-07-04 09:20:45 -0700907 }
908
909 serverExtensions.duplicateExtension = c.config.Bugs.DuplicateExtension
910
911 if len(hs.clientHello.serverName) > 0 {
912 c.serverName = hs.clientHello.serverName
913 }
914 if len(config.Certificates) == 0 {
915 c.sendAlert(alertInternalError)
916 return errors.New("tls: no certificates configured")
917 }
918 hs.cert = &config.Certificates[0]
919 if len(hs.clientHello.serverName) > 0 {
920 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
921 }
922 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
923 return errors.New("tls: unexpected server name")
924 }
925
926 if len(hs.clientHello.alpnProtocols) > 0 {
927 if proto := c.config.Bugs.ALPNProtocol; proto != nil {
928 serverExtensions.alpnProtocol = *proto
929 serverExtensions.alpnProtocolEmpty = len(*proto) == 0
930 c.clientProtocol = *proto
931 c.usedALPN = true
932 } else if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
933 serverExtensions.alpnProtocol = selectedProto
934 c.clientProtocol = selectedProto
935 c.usedALPN = true
936 }
937 }
Nick Harper728eed82016-07-07 17:36:52 -0700938
David Benjamin0c40a962016-08-01 12:05:50 -0400939 if len(c.config.Bugs.SendALPN) > 0 {
940 serverExtensions.alpnProtocol = c.config.Bugs.SendALPN
941 }
942
David Benjamin8d315d72016-07-18 01:03:18 +0200943 if c.vers < VersionTLS13 || config.Bugs.NegotiateNPNAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700944 if len(hs.clientHello.alpnProtocols) == 0 || c.config.Bugs.NegotiateALPNAndNPN {
945 // Although sending an empty NPN extension is reasonable, Firefox has
946 // had a bug around this. Best to send nothing at all if
947 // config.NextProtos is empty. See
948 // https://code.google.com/p/go/issues/detail?id=5445.
949 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
950 serverExtensions.nextProtoNeg = true
951 serverExtensions.nextProtos = config.NextProtos
952 serverExtensions.npnLast = config.Bugs.SwapNPNAndALPN
953 }
David Benjamin7d79f832016-07-04 09:20:45 -0700954 }
Steven Valdez143e8b32016-07-11 13:19:03 -0400955 }
David Benjamin7d79f832016-07-04 09:20:45 -0700956
David Benjamin8d315d72016-07-18 01:03:18 +0200957 if c.vers < VersionTLS13 || config.Bugs.NegotiateEMSAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700958 serverExtensions.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !c.config.Bugs.NoExtendedMasterSecret
Steven Valdez143e8b32016-07-11 13:19:03 -0400959 }
David Benjamin7d79f832016-07-04 09:20:45 -0700960
David Benjamin8d315d72016-07-18 01:03:18 +0200961 if c.vers < VersionTLS13 || config.Bugs.NegotiateChannelIDAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700962 if hs.clientHello.channelIDSupported && config.RequestChannelID {
963 serverExtensions.channelIDRequested = true
964 }
David Benjamin7d79f832016-07-04 09:20:45 -0700965 }
966
967 if hs.clientHello.srtpProtectionProfiles != nil {
968 SRTPLoop:
969 for _, p1 := range c.config.SRTPProtectionProfiles {
970 for _, p2 := range hs.clientHello.srtpProtectionProfiles {
971 if p1 == p2 {
972 serverExtensions.srtpProtectionProfile = p1
973 c.srtpProtectionProfile = p1
974 break SRTPLoop
975 }
976 }
977 }
978 }
979
980 if c.config.Bugs.SendSRTPProtectionProfile != 0 {
981 serverExtensions.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
982 }
983
984 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
985 if hs.clientHello.customExtension != *expected {
986 return fmt.Errorf("tls: bad custom extension contents %q", hs.clientHello.customExtension)
987 }
988 }
989 serverExtensions.customExtension = config.Bugs.CustomExtension
990
Steven Valdez143e8b32016-07-11 13:19:03 -0400991 if c.config.Bugs.AdvertiseTicketExtension {
992 serverExtensions.ticketSupported = true
993 }
994
David Benjamin7d79f832016-07-04 09:20:45 -0700995 return nil
996}
997
Adam Langley95c29f32014-06-20 12:00:00 -0700998// checkForResumption returns true if we should perform resumption on this connection.
999func (hs *serverHandshakeState) checkForResumption() bool {
1000 c := hs.c
1001
David Benjamin405da482016-08-08 17:25:07 -04001002 ticket := hs.clientHello.sessionTicket
1003 if len(ticket) == 0 && len(hs.clientHello.pskIdentities) > 0 && c.config.Bugs.AcceptAnySession {
1004 ticket = hs.clientHello.pskIdentities[0]
1005 }
1006 if len(ticket) > 0 {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001007 if c.config.SessionTicketsDisabled {
1008 return false
1009 }
David Benjaminb0c8db72014-09-24 15:19:56 -04001010
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001011 var ok bool
David Benjamin405da482016-08-08 17:25:07 -04001012 if hs.sessionState, ok = c.decryptTicket(ticket); !ok {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001013 return false
1014 }
1015 } else {
1016 if c.config.ServerSessionCache == nil {
1017 return false
1018 }
1019
1020 var ok bool
1021 sessionId := string(hs.clientHello.sessionId)
1022 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
1023 return false
1024 }
Adam Langley95c29f32014-06-20 12:00:00 -07001025 }
1026
David Benjamin405da482016-08-08 17:25:07 -04001027 if !c.config.Bugs.AcceptAnySession {
1028 // Never resume a session for a different SSL version.
1029 if c.vers != hs.sessionState.vers {
1030 return false
Adam Langley95c29f32014-06-20 12:00:00 -07001031 }
David Benjamin405da482016-08-08 17:25:07 -04001032
1033 cipherSuiteOk := false
1034 // Check that the client is still offering the ciphersuite in the session.
1035 for _, id := range hs.clientHello.cipherSuites {
1036 if id == hs.sessionState.cipherSuite {
1037 cipherSuiteOk = true
1038 break
1039 }
1040 }
1041 if !cipherSuiteOk {
1042 return false
1043 }
Adam Langley95c29f32014-06-20 12:00:00 -07001044 }
1045
1046 // Check that we also support the ciphersuite from the session.
Nick Harper728eed82016-07-07 17:36:52 -07001047 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 -07001048 if hs.suite == nil {
1049 return false
1050 }
1051
1052 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
1053 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
1054 if needClientCerts && !sessionHasClientCerts {
1055 return false
1056 }
1057 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
1058 return false
1059 }
1060
1061 return true
1062}
1063
1064func (hs *serverHandshakeState) doResumeHandshake() error {
1065 c := hs.c
1066
1067 hs.hello.cipherSuite = hs.suite.id
David Benjaminece3de92015-03-16 18:02:20 -04001068 if c.config.Bugs.SendCipherSuite != 0 {
1069 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
1070 }
Adam Langley95c29f32014-06-20 12:00:00 -07001071 // We echo the client's session ID in the ServerHello to let it know
1072 // that we're doing a resumption.
1073 hs.hello.sessionId = hs.clientHello.sessionId
Nick Harperb3d51be2016-07-01 11:43:18 -04001074 hs.hello.extensions.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -07001075
David Benjamin80d1b352016-05-04 19:19:06 -04001076 if c.config.Bugs.SendSCTListOnResume != nil {
Nick Harperb3d51be2016-07-01 11:43:18 -04001077 hs.hello.extensions.sctList = c.config.Bugs.SendSCTListOnResume
David Benjamin80d1b352016-05-04 19:19:06 -04001078 }
1079
Adam Langley95c29f32014-06-20 12:00:00 -07001080 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -04001081 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -04001082 hs.writeClientHash(hs.clientHello.marshal())
1083 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001084
1085 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
1086
1087 if len(hs.sessionState.certificates) > 0 {
1088 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
1089 return err
1090 }
1091 }
1092
1093 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -07001094 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -07001095
1096 return nil
1097}
1098
1099func (hs *serverHandshakeState) doFullHandshake() error {
1100 config := hs.c.config
1101 c := hs.c
1102
David Benjamin48cae082014-10-27 01:06:24 -04001103 isPSK := hs.suite.flags&suitePSK != 0
1104 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001105 hs.hello.extensions.ocspStapling = true
Adam Langley95c29f32014-06-20 12:00:00 -07001106 }
1107
David Benjamin61f95272014-11-25 01:55:35 -05001108 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001109 hs.hello.extensions.sctList = hs.cert.SignedCertificateTimestampList
David Benjamin61f95272014-11-25 01:55:35 -05001110 }
1111
Nick Harperb3d51be2016-07-01 11:43:18 -04001112 hs.hello.extensions.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
Adam Langley95c29f32014-06-20 12:00:00 -07001113 hs.hello.cipherSuite = hs.suite.id
David Benjamin6095de82014-12-27 01:50:38 -05001114 if config.Bugs.SendCipherSuite != 0 {
1115 hs.hello.cipherSuite = config.Bugs.SendCipherSuite
1116 }
Nick Harperb3d51be2016-07-01 11:43:18 -04001117 c.extendedMasterSecret = hs.hello.extensions.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -07001118
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001119 // Generate a session ID if we're to save the session.
Nick Harperb3d51be2016-07-01 11:43:18 -04001120 if !hs.hello.extensions.ticketSupported && config.ServerSessionCache != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001121 hs.hello.sessionId = make([]byte, 32)
1122 if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
1123 c.sendAlert(alertInternalError)
1124 return errors.New("tls: short read from Rand: " + err.Error())
1125 }
1126 }
1127
Adam Langley95c29f32014-06-20 12:00:00 -07001128 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -04001129 hs.writeClientHash(hs.clientHello.marshal())
1130 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001131
1132 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
1133
David Benjamin48cae082014-10-27 01:06:24 -04001134 if !isPSK {
1135 certMsg := new(certificateMsg)
David Benjamin8923c0b2015-06-07 11:42:34 -04001136 if !config.Bugs.EmptyCertificateList {
1137 certMsg.certificates = hs.cert.Certificate
1138 }
David Benjamin48cae082014-10-27 01:06:24 -04001139 if !config.Bugs.UnauthenticatedECDH {
David Benjaminbcb2d912015-02-24 23:45:43 -05001140 certMsgBytes := certMsg.marshal()
David Benjaminbcb2d912015-02-24 23:45:43 -05001141 hs.writeServerHash(certMsgBytes)
1142 c.writeRecord(recordTypeHandshake, certMsgBytes)
David Benjamin48cae082014-10-27 01:06:24 -04001143 }
David Benjamin1c375dd2014-07-12 00:48:23 -04001144 }
Adam Langley95c29f32014-06-20 12:00:00 -07001145
Nick Harperb3d51be2016-07-01 11:43:18 -04001146 if hs.hello.extensions.ocspStapling && !c.config.Bugs.SkipCertificateStatus {
Adam Langley95c29f32014-06-20 12:00:00 -07001147 certStatus := new(certificateStatusMsg)
1148 certStatus.statusType = statusTypeOCSP
1149 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -04001150 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001151 c.writeRecord(recordTypeHandshake, certStatus.marshal())
1152 }
1153
1154 keyAgreement := hs.suite.ka(c.vers)
1155 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
1156 if err != nil {
1157 c.sendAlert(alertHandshakeFailure)
1158 return err
1159 }
Steven Valdez5440fe02016-07-18 12:40:30 -04001160 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
1161 c.curveID = ecdhe.curveID
1162 }
David Benjamin9c651c92014-07-12 13:27:45 -04001163 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -04001164 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001165 c.writeRecord(recordTypeHandshake, skx.marshal())
1166 }
1167
1168 if config.ClientAuth >= RequestClientCert {
1169 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -04001170 certReq := &certificateRequestMsg{
1171 certificateTypes: config.ClientCertificateTypes,
1172 }
1173 if certReq.certificateTypes == nil {
1174 certReq.certificateTypes = []byte{
1175 byte(CertTypeRSASign),
1176 byte(CertTypeECDSASign),
1177 }
Adam Langley95c29f32014-06-20 12:00:00 -07001178 }
1179 if c.vers >= VersionTLS12 {
Nick Harper60edffd2016-06-21 15:19:24 -07001180 certReq.hasSignatureAlgorithm = true
1181 if !config.Bugs.NoSignatureAlgorithms {
David Benjamin7a41d372016-07-09 11:21:54 -07001182 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin000800a2014-11-14 01:43:59 -05001183 }
Adam Langley95c29f32014-06-20 12:00:00 -07001184 }
1185
1186 // An empty list of certificateAuthorities signals to
1187 // the client that it may send any certificate in response
1188 // to our request. When we know the CAs we trust, then
1189 // we can send them down, so that the client can choose
1190 // an appropriate certificate to give to us.
1191 if config.ClientCAs != nil {
1192 certReq.certificateAuthorities = config.ClientCAs.Subjects()
1193 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001194 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001195 c.writeRecord(recordTypeHandshake, certReq.marshal())
1196 }
1197
1198 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001199 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001200 c.writeRecord(recordTypeHandshake, helloDone.marshal())
David Benjamin582ba042016-07-07 12:33:25 -07001201 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001202
1203 var pub crypto.PublicKey // public key for client auth, if any
1204
David Benjamin83f90402015-01-27 01:09:43 -05001205 if err := c.simulatePacketLoss(nil); err != nil {
1206 return err
1207 }
Adam Langley95c29f32014-06-20 12:00:00 -07001208 msg, err := c.readHandshake()
1209 if err != nil {
1210 return err
1211 }
1212
1213 var ok bool
1214 // If we requested a client certificate, then the client must send a
1215 // certificate message, even if it's empty.
1216 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -04001217 var certMsg *certificateMsg
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001218 var certificates [][]byte
1219 if certMsg, ok = msg.(*certificateMsg); ok {
1220 if c.vers == VersionSSL30 && len(certMsg.certificates) == 0 {
1221 return errors.New("tls: empty certificate message in SSL 3.0")
1222 }
1223
1224 hs.writeClientHash(certMsg.marshal())
1225 certificates = certMsg.certificates
1226 } else if c.vers != VersionSSL30 {
1227 // In TLS, the Certificate message is required. In SSL
1228 // 3.0, the peer skips it when sending no certificates.
Adam Langley95c29f32014-06-20 12:00:00 -07001229 c.sendAlert(alertUnexpectedMessage)
1230 return unexpectedMessageError(certMsg, msg)
1231 }
Adam Langley95c29f32014-06-20 12:00:00 -07001232
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001233 if len(certificates) == 0 {
Adam Langley95c29f32014-06-20 12:00:00 -07001234 // The client didn't actually send a certificate
1235 switch config.ClientAuth {
1236 case RequireAnyClientCert, RequireAndVerifyClientCert:
1237 c.sendAlert(alertBadCertificate)
1238 return errors.New("tls: client didn't provide a certificate")
1239 }
1240 }
1241
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001242 pub, err = hs.processCertsFromClient(certificates)
Adam Langley95c29f32014-06-20 12:00:00 -07001243 if err != nil {
1244 return err
1245 }
1246
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001247 if ok {
1248 msg, err = c.readHandshake()
1249 if err != nil {
1250 return err
1251 }
Adam Langley95c29f32014-06-20 12:00:00 -07001252 }
1253 }
1254
1255 // Get client key exchange
1256 ckx, ok := msg.(*clientKeyExchangeMsg)
1257 if !ok {
1258 c.sendAlert(alertUnexpectedMessage)
1259 return unexpectedMessageError(ckx, msg)
1260 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001261 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001262
David Benjamine098ec22014-08-27 23:13:20 -04001263 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
1264 if err != nil {
1265 c.sendAlert(alertHandshakeFailure)
1266 return err
1267 }
Adam Langley75712922014-10-10 16:23:43 -07001268 if c.extendedMasterSecret {
1269 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1270 } else {
1271 if c.config.Bugs.RequireExtendedMasterSecret {
1272 return errors.New("tls: extended master secret required but not supported by peer")
1273 }
1274 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
1275 }
David Benjamine098ec22014-08-27 23:13:20 -04001276
Adam Langley95c29f32014-06-20 12:00:00 -07001277 // If we received a client cert in response to our certificate request message,
1278 // the client will send us a certificateVerifyMsg immediately after the
1279 // clientKeyExchangeMsg. This message is a digest of all preceding
1280 // handshake-layer messages that is signed using the private key corresponding
1281 // to the client's certificate. This allows us to verify that the client is in
1282 // possession of the private key of the certificate.
1283 if len(c.peerCertificates) > 0 {
1284 msg, err = c.readHandshake()
1285 if err != nil {
1286 return err
1287 }
1288 certVerify, ok := msg.(*certificateVerifyMsg)
1289 if !ok {
1290 c.sendAlert(alertUnexpectedMessage)
1291 return unexpectedMessageError(certVerify, msg)
1292 }
1293
David Benjaminde620d92014-07-18 15:03:41 -04001294 // Determine the signature type.
Nick Harper60edffd2016-06-21 15:19:24 -07001295 var sigAlg signatureAlgorithm
1296 if certVerify.hasSignatureAlgorithm {
1297 sigAlg = certVerify.signatureAlgorithm
Nick Harper60edffd2016-06-21 15:19:24 -07001298 c.peerSignatureAlgorithm = sigAlg
David Benjaminde620d92014-07-18 15:03:41 -04001299 }
1300
Nick Harper60edffd2016-06-21 15:19:24 -07001301 if c.vers > VersionSSL30 {
David Benjamin1fb125c2016-07-08 18:52:12 -07001302 err = verifyMessage(c.vers, pub, c.config, sigAlg, hs.finishedHash.buffer, certVerify.signature)
Nick Harper60edffd2016-06-21 15:19:24 -07001303 } else {
1304 // SSL 3.0's client certificate construction is
1305 // incompatible with signatureAlgorithm.
1306 rsaPub, ok := pub.(*rsa.PublicKey)
1307 if !ok {
1308 err = errors.New("unsupported key type for client certificate")
1309 } else {
1310 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
1311 err = rsa.VerifyPKCS1v15(rsaPub, crypto.MD5SHA1, digest, certVerify.signature)
David Benjaminde620d92014-07-18 15:03:41 -04001312 }
Adam Langley95c29f32014-06-20 12:00:00 -07001313 }
1314 if err != nil {
1315 c.sendAlert(alertBadCertificate)
1316 return errors.New("could not validate signature of connection nonces: " + err.Error())
1317 }
1318
David Benjamin83c0bc92014-08-04 01:23:53 -04001319 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001320 }
1321
David Benjamine098ec22014-08-27 23:13:20 -04001322 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001323
1324 return nil
1325}
1326
1327func (hs *serverHandshakeState) establishKeys() error {
1328 c := hs.c
1329
1330 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001331 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 -07001332
1333 var clientCipher, serverCipher interface{}
1334 var clientHash, serverHash macFunction
1335
1336 if hs.suite.aead == nil {
1337 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
1338 clientHash = hs.suite.mac(c.vers, clientMAC)
1339 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
1340 serverHash = hs.suite.mac(c.vers, serverMAC)
1341 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001342 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1343 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001344 }
1345
1346 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
1347 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
1348
1349 return nil
1350}
1351
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001352func (hs *serverHandshakeState) readFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001353 c := hs.c
1354
1355 c.readRecord(recordTypeChangeCipherSpec)
1356 if err := c.in.error(); err != nil {
1357 return err
1358 }
1359
Nick Harperb3d51be2016-07-01 11:43:18 -04001360 if hs.hello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001361 msg, err := c.readHandshake()
1362 if err != nil {
1363 return err
1364 }
1365 nextProto, ok := msg.(*nextProtoMsg)
1366 if !ok {
1367 c.sendAlert(alertUnexpectedMessage)
1368 return unexpectedMessageError(nextProto, msg)
1369 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001370 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001371 c.clientProtocol = nextProto.proto
1372 }
1373
Nick Harperb3d51be2016-07-01 11:43:18 -04001374 if hs.hello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001375 msg, err := c.readHandshake()
1376 if err != nil {
1377 return err
1378 }
David Benjamin24599a82016-06-30 18:56:53 -04001379 channelIDMsg, ok := msg.(*channelIDMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001380 if !ok {
1381 c.sendAlert(alertUnexpectedMessage)
David Benjamin24599a82016-06-30 18:56:53 -04001382 return unexpectedMessageError(channelIDMsg, msg)
David Benjamind30a9902014-08-24 01:44:23 -04001383 }
David Benjamin24599a82016-06-30 18:56:53 -04001384 x := new(big.Int).SetBytes(channelIDMsg.channelID[0:32])
1385 y := new(big.Int).SetBytes(channelIDMsg.channelID[32:64])
1386 r := new(big.Int).SetBytes(channelIDMsg.channelID[64:96])
1387 s := new(big.Int).SetBytes(channelIDMsg.channelID[96:128])
David Benjamind30a9902014-08-24 01:44:23 -04001388 if !elliptic.P256().IsOnCurve(x, y) {
1389 return errors.New("tls: invalid channel ID public key")
1390 }
1391 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
1392 var resumeHash []byte
1393 if isResume {
1394 resumeHash = hs.sessionState.handshakeHash
1395 }
1396 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
1397 return errors.New("tls: invalid channel ID signature")
1398 }
1399 c.channelID = channelID
1400
David Benjamin24599a82016-06-30 18:56:53 -04001401 hs.writeClientHash(channelIDMsg.marshal())
David Benjamind30a9902014-08-24 01:44:23 -04001402 }
1403
Adam Langley95c29f32014-06-20 12:00:00 -07001404 msg, err := c.readHandshake()
1405 if err != nil {
1406 return err
1407 }
1408 clientFinished, ok := msg.(*finishedMsg)
1409 if !ok {
1410 c.sendAlert(alertUnexpectedMessage)
1411 return unexpectedMessageError(clientFinished, msg)
1412 }
1413
1414 verify := hs.finishedHash.clientSum(hs.masterSecret)
1415 if len(verify) != len(clientFinished.verifyData) ||
1416 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
1417 c.sendAlert(alertHandshakeFailure)
1418 return errors.New("tls: client's Finished message is incorrect")
1419 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001420 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001421 copy(out, clientFinished.verifyData)
Adam Langley95c29f32014-06-20 12:00:00 -07001422
David Benjamin83c0bc92014-08-04 01:23:53 -04001423 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001424 return nil
1425}
1426
1427func (hs *serverHandshakeState) sendSessionTicket() error {
Adam Langley95c29f32014-06-20 12:00:00 -07001428 c := hs.c
Adam Langley95c29f32014-06-20 12:00:00 -07001429 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -04001430 vers: c.vers,
1431 cipherSuite: hs.suite.id,
1432 masterSecret: hs.masterSecret,
1433 certificates: hs.certsFromClient,
1434 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -07001435 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001436
Nick Harperb3d51be2016-07-01 11:43:18 -04001437 if !hs.hello.extensions.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001438 if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
1439 c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
1440 }
1441 return nil
1442 }
1443
1444 m := new(newSessionTicketMsg)
1445
David Benjamindd6fed92015-10-23 17:41:12 -04001446 if !c.config.Bugs.SendEmptySessionTicket {
1447 var err error
1448 m.ticket, err = c.encryptTicket(&state)
1449 if err != nil {
1450 return err
1451 }
Adam Langley95c29f32014-06-20 12:00:00 -07001452 }
Adam Langley95c29f32014-06-20 12:00:00 -07001453
David Benjamin83c0bc92014-08-04 01:23:53 -04001454 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001455 c.writeRecord(recordTypeHandshake, m.marshal())
1456
1457 return nil
1458}
1459
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001460func (hs *serverHandshakeState) sendFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001461 c := hs.c
1462
David Benjamin86271ee2014-07-21 16:14:03 -04001463 finished := new(finishedMsg)
1464 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001465 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001466 if c.config.Bugs.BadFinished {
1467 finished.verifyData[0]++
1468 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001469 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001470 hs.finishedBytes = finished.marshal()
1471 hs.writeServerHash(hs.finishedBytes)
1472 postCCSBytes := hs.finishedBytes
David Benjamin86271ee2014-07-21 16:14:03 -04001473
1474 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
1475 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
1476 postCCSBytes = postCCSBytes[5:]
David Benjamin61672812016-07-14 23:10:43 -04001477 } else if c.config.Bugs.SendUnencryptedFinished {
1478 c.writeRecord(recordTypeHandshake, postCCSBytes)
1479 postCCSBytes = nil
David Benjamin86271ee2014-07-21 16:14:03 -04001480 }
David Benjamin582ba042016-07-07 12:33:25 -07001481 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001482
David Benjamina0e52232014-07-19 17:39:58 -04001483 if !c.config.Bugs.SkipChangeCipherSpec {
David Benjamin8411b242015-11-26 12:07:28 -05001484 ccs := []byte{1}
1485 if c.config.Bugs.BadChangeCipherSpec != nil {
1486 ccs = c.config.Bugs.BadChangeCipherSpec
1487 }
1488 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamina0e52232014-07-19 17:39:58 -04001489 }
Adam Langley95c29f32014-06-20 12:00:00 -07001490
David Benjamin4189bd92015-01-25 23:52:39 -05001491 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1492 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1493 }
David Benjamindc3da932015-03-12 15:09:02 -04001494 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1495 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1496 return errors.New("tls: simulating post-CCS alert")
1497 }
David Benjamin4189bd92015-01-25 23:52:39 -05001498
David Benjamin61672812016-07-14 23:10:43 -04001499 if !c.config.Bugs.SkipFinished && len(postCCSBytes) > 0 {
David Benjaminb80168e2015-02-08 18:30:14 -05001500 c.writeRecord(recordTypeHandshake, postCCSBytes)
David Benjamin02edcd02016-07-27 17:40:37 -04001501 if c.config.Bugs.SendExtraFinished {
1502 c.writeRecord(recordTypeHandshake, finished.marshal())
1503 }
1504
David Benjamin12d2c482016-07-24 10:56:51 -04001505 if !c.config.Bugs.PackHelloRequestWithFinished {
1506 // Defer flushing until renegotiation.
1507 c.flushHandshake()
1508 }
David Benjaminb3774b92015-01-31 17:16:01 -05001509 }
Adam Langley95c29f32014-06-20 12:00:00 -07001510
David Benjaminc565ebb2015-04-03 04:06:36 -04001511 c.cipherSuite = hs.suite
Adam Langley95c29f32014-06-20 12:00:00 -07001512
1513 return nil
1514}
1515
1516// processCertsFromClient takes a chain of client certificates either from a
1517// Certificates message or from a sessionState and verifies them. It returns
1518// the public key of the leaf certificate.
1519func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
1520 c := hs.c
1521
1522 hs.certsFromClient = certificates
1523 certs := make([]*x509.Certificate, len(certificates))
1524 var err error
1525 for i, asn1Data := range certificates {
1526 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
1527 c.sendAlert(alertBadCertificate)
1528 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
1529 }
1530 }
1531
1532 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
1533 opts := x509.VerifyOptions{
1534 Roots: c.config.ClientCAs,
1535 CurrentTime: c.config.time(),
1536 Intermediates: x509.NewCertPool(),
1537 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
1538 }
1539
1540 for _, cert := range certs[1:] {
1541 opts.Intermediates.AddCert(cert)
1542 }
1543
1544 chains, err := certs[0].Verify(opts)
1545 if err != nil {
1546 c.sendAlert(alertBadCertificate)
1547 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
1548 }
1549
1550 ok := false
1551 for _, ku := range certs[0].ExtKeyUsage {
1552 if ku == x509.ExtKeyUsageClientAuth {
1553 ok = true
1554 break
1555 }
1556 }
1557 if !ok {
1558 c.sendAlert(alertHandshakeFailure)
1559 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
1560 }
1561
1562 c.verifiedChains = chains
1563 }
1564
1565 if len(certs) > 0 {
1566 var pub crypto.PublicKey
1567 switch key := certs[0].PublicKey.(type) {
1568 case *ecdsa.PublicKey, *rsa.PublicKey:
1569 pub = key
1570 default:
1571 c.sendAlert(alertUnsupportedCertificate)
1572 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
1573 }
1574 c.peerCertificates = certs
1575 return pub, nil
1576 }
1577
1578 return nil, nil
1579}
1580
David Benjamin83c0bc92014-08-04 01:23:53 -04001581func (hs *serverHandshakeState) writeServerHash(msg []byte) {
1582 // writeServerHash is called before writeRecord.
1583 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1584}
1585
1586func (hs *serverHandshakeState) writeClientHash(msg []byte) {
1587 // writeClientHash is called after readHandshake.
1588 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1589}
1590
1591func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
1592 if hs.c.isDTLS {
1593 // This is somewhat hacky. DTLS hashes a slightly different format.
1594 // First, the TLS header.
1595 hs.finishedHash.Write(msg[:4])
1596 // Then the sequence number and reassembled fragment offset (always 0).
1597 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1598 // Then the reassembled fragment (always equal to the message length).
1599 hs.finishedHash.Write(msg[1:4])
1600 // And then the message body.
1601 hs.finishedHash.Write(msg[4:])
1602 } else {
1603 hs.finishedHash.Write(msg)
1604 }
1605}
1606
Adam Langley95c29f32014-06-20 12:00:00 -07001607// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
1608// is acceptable to use.
Nick Harper728eed82016-07-07 17:36:52 -07001609func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk, pskOk bool) *cipherSuite {
Adam Langley95c29f32014-06-20 12:00:00 -07001610 for _, supported := range supportedCipherSuites {
1611 if id == supported {
1612 var candidate *cipherSuite
1613
1614 for _, s := range cipherSuites {
1615 if s.id == id {
1616 candidate = s
1617 break
1618 }
1619 }
1620 if candidate == nil {
1621 continue
1622 }
1623 // Don't select a ciphersuite which we can't
1624 // support for this client.
David Benjamin0407e762016-06-17 16:41:18 -04001625 if !c.config.Bugs.EnableAllCiphers {
Nick Harper728eed82016-07-07 17:36:52 -07001626 if (candidate.flags&suitePSK != 0) && !pskOk {
1627 continue
1628 }
David Benjamin0407e762016-06-17 16:41:18 -04001629 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
1630 continue
1631 }
1632 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
1633 continue
1634 }
1635 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
1636 continue
1637 }
Nick Harper728eed82016-07-07 17:36:52 -07001638 if version >= VersionTLS13 && candidate.flags&suiteTLS13 == 0 {
1639 continue
1640 }
David Benjamin0407e762016-06-17 16:41:18 -04001641 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
1642 continue
1643 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001644 }
Adam Langley95c29f32014-06-20 12:00:00 -07001645 return candidate
1646 }
1647 }
1648
1649 return nil
1650}
David Benjaminf93995b2015-11-05 18:23:20 -05001651
1652func isTLS12Cipher(id uint16) bool {
1653 for _, cipher := range cipherSuites {
1654 if cipher.id != id {
1655 continue
1656 }
1657 return cipher.flags&suiteTLS12 != 0
1658 }
1659 // Unknown cipher.
1660 return false
1661}