blob: 6d4d70a1700b06f035ba176b0b5983b0fbf03908 [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,
David Benjamin8a8349b2016-08-18 02:32:23 -0400599 requestContext: config.Bugs.SendRequestContext,
David Benjamin8d343b42016-07-09 14:26:01 -0700600 }
601 if !config.Bugs.NoSignatureAlgorithms {
David Benjaminf74ec792016-07-13 21:18:49 -0400602 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin8d343b42016-07-09 14:26:01 -0700603 }
604
605 // An empty list of certificateAuthorities signals to
606 // the client that it may send any certificate in response
607 // to our request. When we know the CAs we trust, then
608 // we can send them down, so that the client can choose
609 // an appropriate certificate to give to us.
610 if config.ClientCAs != nil {
611 certReq.certificateAuthorities = config.ClientCAs.Subjects()
612 }
613 hs.writeServerHash(certReq.marshal())
614 c.writeRecord(recordTypeHandshake, certReq.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700615 }
616
617 certMsg := &certificateMsg{
618 hasRequestContext: true,
619 }
620 if !config.Bugs.EmptyCertificateList {
621 certMsg.certificates = hs.cert.Certificate
622 }
David Benjamin1edae6b2016-07-13 16:58:23 -0400623 certMsgBytes := certMsg.marshal()
David Benjamin1edae6b2016-07-13 16:58:23 -0400624 hs.writeServerHash(certMsgBytes)
625 c.writeRecord(recordTypeHandshake, certMsgBytes)
Nick Harper728eed82016-07-07 17:36:52 -0700626
627 certVerify := &certificateVerifyMsg{
628 hasSignatureAlgorithm: true,
629 }
630
631 // Determine the hash to sign.
632 privKey := hs.cert.PrivateKey
633
634 var err error
635 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, config, hs.clientHello.signatureAlgorithms)
636 if err != nil {
637 c.sendAlert(alertInternalError)
638 return err
639 }
640
641 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
642 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
643 if err != nil {
644 c.sendAlert(alertInternalError)
645 return err
646 }
647
Steven Valdez0ee2e112016-07-15 06:51:15 -0400648 if config.Bugs.SendSignatureAlgorithm != 0 {
649 certVerify.signatureAlgorithm = config.Bugs.SendSignatureAlgorithm
650 }
651
Nick Harper728eed82016-07-07 17:36:52 -0700652 hs.writeServerHash(certVerify.marshal())
653 c.writeRecord(recordTypeHandshake, certVerify.marshal())
Nick Harper0b3625b2016-07-25 16:16:28 -0700654 } else {
655 // Pick up certificates from the session instead.
656 // hs.sessionState may be nil if config.Bugs.EnableAllCiphers is
657 // true.
658 if hs.sessionState != nil && len(hs.sessionState.certificates) > 0 {
659 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
660 return err
661 }
662 }
Nick Harper728eed82016-07-07 17:36:52 -0700663 }
664
665 finished := new(finishedMsg)
666 finished.verifyData = hs.finishedHash.serverSum(handshakeTrafficSecret)
667 if config.Bugs.BadFinished {
668 finished.verifyData[0]++
669 }
670 hs.writeServerHash(finished.marshal())
671 c.writeRecord(recordTypeHandshake, finished.marshal())
David Benjamin02edcd02016-07-27 17:40:37 -0400672 if c.config.Bugs.SendExtraFinished {
673 c.writeRecord(recordTypeHandshake, finished.marshal())
674 }
Nick Harper728eed82016-07-07 17:36:52 -0700675 c.flushHandshake()
676
677 // The various secrets do not incorporate the client's final leg, so
678 // derive them now before updating the handshake context.
679 masterSecret := hs.finishedHash.extractKey(handshakeSecret, hs.finishedHash.zeroSecret())
680 trafficSecret := hs.finishedHash.deriveSecret(masterSecret, applicationTrafficLabel)
681
David Benjamin2aad4062016-07-14 23:15:40 -0400682 // Switch to application data keys on write. In particular, any alerts
683 // from the client certificate are sent over these keys.
David Benjamin21c00282016-07-18 21:56:23 +0200684 c.out.useTrafficSecret(c.vers, hs.suite, trafficSecret, applicationPhase, serverWrite)
David Benjamin2aad4062016-07-14 23:15:40 -0400685
Nick Harper728eed82016-07-07 17:36:52 -0700686 // If we requested a client certificate, then the client must send a
687 // certificate message, even if it's empty.
688 if config.ClientAuth >= RequestClientCert {
David Benjamin8d343b42016-07-09 14:26:01 -0700689 msg, err := c.readHandshake()
690 if err != nil {
691 return err
692 }
693
694 certMsg, ok := msg.(*certificateMsg)
695 if !ok {
696 c.sendAlert(alertUnexpectedMessage)
697 return unexpectedMessageError(certMsg, msg)
698 }
699 hs.writeClientHash(certMsg.marshal())
700
701 if len(certMsg.certificates) == 0 {
702 // The client didn't actually send a certificate
703 switch config.ClientAuth {
704 case RequireAnyClientCert, RequireAndVerifyClientCert:
705 c.sendAlert(alertBadCertificate)
706 return errors.New("tls: client didn't provide a certificate")
707 }
708 }
709
710 pub, err := hs.processCertsFromClient(certMsg.certificates)
711 if err != nil {
712 return err
713 }
714
715 if len(c.peerCertificates) > 0 {
716 msg, err = c.readHandshake()
717 if err != nil {
718 return err
719 }
720
721 certVerify, ok := msg.(*certificateVerifyMsg)
722 if !ok {
723 c.sendAlert(alertUnexpectedMessage)
724 return unexpectedMessageError(certVerify, msg)
725 }
726
David Benjaminf74ec792016-07-13 21:18:49 -0400727 c.peerSignatureAlgorithm = certVerify.signatureAlgorithm
David Benjamin8d343b42016-07-09 14:26:01 -0700728 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
729 if err := verifyMessage(c.vers, pub, config, certVerify.signatureAlgorithm, input, certVerify.signature); err != nil {
730 c.sendAlert(alertBadCertificate)
731 return err
732 }
733 hs.writeClientHash(certVerify.marshal())
734 }
Nick Harper728eed82016-07-07 17:36:52 -0700735 }
736
737 // Read the client Finished message.
738 msg, err := c.readHandshake()
739 if err != nil {
740 return err
741 }
742 clientFinished, ok := msg.(*finishedMsg)
743 if !ok {
744 c.sendAlert(alertUnexpectedMessage)
745 return unexpectedMessageError(clientFinished, msg)
746 }
747
748 verify := hs.finishedHash.clientSum(handshakeTrafficSecret)
749 if len(verify) != len(clientFinished.verifyData) ||
750 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
751 c.sendAlert(alertHandshakeFailure)
752 return errors.New("tls: client's Finished message was incorrect")
753 }
David Benjamin97a0a082016-07-13 17:57:35 -0400754 hs.writeClientHash(clientFinished.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700755
David Benjamin2aad4062016-07-14 23:15:40 -0400756 // Switch to application data keys on read.
David Benjamin21c00282016-07-18 21:56:23 +0200757 c.in.useTrafficSecret(c.vers, hs.suite, trafficSecret, applicationPhase, clientWrite)
Nick Harper728eed82016-07-07 17:36:52 -0700758
Nick Harper728eed82016-07-07 17:36:52 -0700759 c.cipherSuite = hs.suite
David Benjamin97a0a082016-07-13 17:57:35 -0400760 c.exporterSecret = hs.finishedHash.deriveSecret(masterSecret, exporterLabel)
David Benjamin58104882016-07-18 01:25:41 +0200761 c.resumptionSecret = hs.finishedHash.deriveSecret(masterSecret, resumptionLabel)
762
763 // TODO(davidben): Allow configuring the number of tickets sent for
764 // testing.
765 if !c.config.SessionTicketsDisabled {
766 ticketCount := 2
767 for i := 0; i < ticketCount; i++ {
768 c.SendNewSessionTicket()
769 }
770 }
Nick Harper728eed82016-07-07 17:36:52 -0700771 return nil
772}
773
David Benjaminf25dda92016-07-04 10:05:26 -0700774// processClientHello processes the ClientHello message from the client and
775// decides whether we will perform session resumption.
776func (hs *serverHandshakeState) processClientHello() (isResume bool, err error) {
777 config := hs.c.config
778 c := hs.c
779
780 hs.hello = &serverHelloMsg{
781 isDTLS: c.isDTLS,
782 vers: c.vers,
783 compressionMethod: compressionNone,
784 }
785
Steven Valdez5440fe02016-07-18 12:40:30 -0400786 if config.Bugs.SendServerHelloVersion != 0 {
787 hs.hello.vers = config.Bugs.SendServerHelloVersion
788 }
789
David Benjaminf25dda92016-07-04 10:05:26 -0700790 hs.hello.random = make([]byte, 32)
791 _, err = io.ReadFull(config.rand(), hs.hello.random)
792 if err != nil {
793 c.sendAlert(alertInternalError)
794 return false, err
795 }
David Benjamin1f61f0d2016-07-10 12:20:35 -0400796 // Signal downgrades in the server random, per draft-ietf-tls-tls13-14,
797 // section 6.3.1.2.
Nick Harper85f20c22016-07-04 10:11:59 -0700798 if c.vers <= VersionTLS12 && config.maxVersion(c.isDTLS) >= VersionTLS13 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400799 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS13)
Nick Harper85f20c22016-07-04 10:11:59 -0700800 }
801 if c.vers <= VersionTLS11 && config.maxVersion(c.isDTLS) == VersionTLS12 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400802 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS12)
Nick Harper85f20c22016-07-04 10:11:59 -0700803 }
David Benjaminf25dda92016-07-04 10:05:26 -0700804
805 foundCompression := false
806 // We only support null compression, so check that the client offered it.
807 for _, compression := range hs.clientHello.compressionMethods {
808 if compression == compressionNone {
809 foundCompression = true
810 break
811 }
812 }
813
814 if !foundCompression {
815 c.sendAlert(alertHandshakeFailure)
816 return false, errors.New("tls: client does not support uncompressed connections")
817 }
David Benjamin7d79f832016-07-04 09:20:45 -0700818
819 if err := hs.processClientExtensions(&hs.hello.extensions); err != nil {
820 return false, err
Adam Langley09505632015-07-30 18:10:13 -0700821 }
Adam Langley95c29f32014-06-20 12:00:00 -0700822
823 supportedCurve := false
824 preferredCurves := config.curvePreferences()
825Curves:
826 for _, curve := range hs.clientHello.supportedCurves {
827 for _, supported := range preferredCurves {
828 if supported == curve {
829 supportedCurve = true
830 break Curves
831 }
832 }
833 }
834
835 supportedPointFormat := false
836 for _, pointFormat := range hs.clientHello.supportedPoints {
837 if pointFormat == pointFormatUncompressed {
838 supportedPointFormat = true
839 break
840 }
841 }
842 hs.ellipticOk = supportedCurve && supportedPointFormat
843
Adam Langley95c29f32014-06-20 12:00:00 -0700844 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
845
David Benjamin4b27d9f2015-05-12 22:42:52 -0400846 // For test purposes, check that the peer never offers a session when
847 // renegotiating.
848 if c.cipherSuite != nil && len(hs.clientHello.sessionId) > 0 && c.config.Bugs.FailIfResumeOnRenego {
849 return false, errors.New("tls: offered resumption on renegotiation")
850 }
851
David Benjamindd6fed92015-10-23 17:41:12 -0400852 if c.config.Bugs.FailIfSessionOffered && (len(hs.clientHello.sessionTicket) > 0 || len(hs.clientHello.sessionId) > 0) {
853 return false, errors.New("tls: client offered a session ticket or ID")
854 }
855
Adam Langley95c29f32014-06-20 12:00:00 -0700856 if hs.checkForResumption() {
857 return true, nil
858 }
859
Adam Langley95c29f32014-06-20 12:00:00 -0700860 var preferenceList, supportedList []uint16
861 if c.config.PreferServerCipherSuites {
862 preferenceList = c.config.cipherSuites()
863 supportedList = hs.clientHello.cipherSuites
864 } else {
865 preferenceList = hs.clientHello.cipherSuites
866 supportedList = c.config.cipherSuites()
867 }
868
869 for _, id := range preferenceList {
Nick Harper728eed82016-07-07 17:36:52 -0700870 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk, true); hs.suite != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700871 break
872 }
873 }
874
875 if hs.suite == nil {
876 c.sendAlert(alertHandshakeFailure)
877 return false, errors.New("tls: no cipher suite supported by both client and server")
878 }
879
880 return false, nil
881}
882
David Benjamin7d79f832016-07-04 09:20:45 -0700883// processClientExtensions processes all ClientHello extensions not directly
884// related to cipher suite negotiation and writes responses in serverExtensions.
885func (hs *serverHandshakeState) processClientExtensions(serverExtensions *serverExtensions) error {
886 config := hs.c.config
887 c := hs.c
888
David Benjamin8d315d72016-07-18 01:03:18 +0200889 if c.vers < VersionTLS13 || config.Bugs.NegotiateRenegotiationInfoAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700890 if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) {
891 c.sendAlert(alertHandshakeFailure)
892 return errors.New("tls: renegotiation mismatch")
David Benjamin7d79f832016-07-04 09:20:45 -0700893 }
David Benjamin7d79f832016-07-04 09:20:45 -0700894
Nick Harper728eed82016-07-07 17:36:52 -0700895 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
896 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.clientVerify...)
897 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.serverVerify...)
898 if c.config.Bugs.BadRenegotiationInfo {
899 serverExtensions.secureRenegotiation[0] ^= 0x80
900 }
901 } else {
902 serverExtensions.secureRenegotiation = hs.clientHello.secureRenegotiation
903 }
904
905 if c.noRenegotiationInfo() {
906 serverExtensions.secureRenegotiation = nil
907 }
David Benjamin7d79f832016-07-04 09:20:45 -0700908 }
909
910 serverExtensions.duplicateExtension = c.config.Bugs.DuplicateExtension
911
912 if len(hs.clientHello.serverName) > 0 {
913 c.serverName = hs.clientHello.serverName
914 }
915 if len(config.Certificates) == 0 {
916 c.sendAlert(alertInternalError)
917 return errors.New("tls: no certificates configured")
918 }
919 hs.cert = &config.Certificates[0]
920 if len(hs.clientHello.serverName) > 0 {
921 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
922 }
923 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
924 return errors.New("tls: unexpected server name")
925 }
926
927 if len(hs.clientHello.alpnProtocols) > 0 {
928 if proto := c.config.Bugs.ALPNProtocol; proto != nil {
929 serverExtensions.alpnProtocol = *proto
930 serverExtensions.alpnProtocolEmpty = len(*proto) == 0
931 c.clientProtocol = *proto
932 c.usedALPN = true
933 } else if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
934 serverExtensions.alpnProtocol = selectedProto
935 c.clientProtocol = selectedProto
936 c.usedALPN = true
937 }
938 }
Nick Harper728eed82016-07-07 17:36:52 -0700939
David Benjamin0c40a962016-08-01 12:05:50 -0400940 if len(c.config.Bugs.SendALPN) > 0 {
941 serverExtensions.alpnProtocol = c.config.Bugs.SendALPN
942 }
943
David Benjamin8d315d72016-07-18 01:03:18 +0200944 if c.vers < VersionTLS13 || config.Bugs.NegotiateNPNAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700945 if len(hs.clientHello.alpnProtocols) == 0 || c.config.Bugs.NegotiateALPNAndNPN {
946 // Although sending an empty NPN extension is reasonable, Firefox has
947 // had a bug around this. Best to send nothing at all if
948 // config.NextProtos is empty. See
949 // https://code.google.com/p/go/issues/detail?id=5445.
950 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
951 serverExtensions.nextProtoNeg = true
952 serverExtensions.nextProtos = config.NextProtos
953 serverExtensions.npnLast = config.Bugs.SwapNPNAndALPN
954 }
David Benjamin7d79f832016-07-04 09:20:45 -0700955 }
Steven Valdez143e8b32016-07-11 13:19:03 -0400956 }
David Benjamin7d79f832016-07-04 09:20:45 -0700957
David Benjamin8d315d72016-07-18 01:03:18 +0200958 if c.vers < VersionTLS13 || config.Bugs.NegotiateEMSAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700959 serverExtensions.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !c.config.Bugs.NoExtendedMasterSecret
Steven Valdez143e8b32016-07-11 13:19:03 -0400960 }
David Benjamin7d79f832016-07-04 09:20:45 -0700961
David Benjamin8d315d72016-07-18 01:03:18 +0200962 if c.vers < VersionTLS13 || config.Bugs.NegotiateChannelIDAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700963 if hs.clientHello.channelIDSupported && config.RequestChannelID {
964 serverExtensions.channelIDRequested = true
965 }
David Benjamin7d79f832016-07-04 09:20:45 -0700966 }
967
968 if hs.clientHello.srtpProtectionProfiles != nil {
969 SRTPLoop:
970 for _, p1 := range c.config.SRTPProtectionProfiles {
971 for _, p2 := range hs.clientHello.srtpProtectionProfiles {
972 if p1 == p2 {
973 serverExtensions.srtpProtectionProfile = p1
974 c.srtpProtectionProfile = p1
975 break SRTPLoop
976 }
977 }
978 }
979 }
980
981 if c.config.Bugs.SendSRTPProtectionProfile != 0 {
982 serverExtensions.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
983 }
984
985 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
986 if hs.clientHello.customExtension != *expected {
987 return fmt.Errorf("tls: bad custom extension contents %q", hs.clientHello.customExtension)
988 }
989 }
990 serverExtensions.customExtension = config.Bugs.CustomExtension
991
Steven Valdez143e8b32016-07-11 13:19:03 -0400992 if c.config.Bugs.AdvertiseTicketExtension {
993 serverExtensions.ticketSupported = true
994 }
995
David Benjamin7d79f832016-07-04 09:20:45 -0700996 return nil
997}
998
Adam Langley95c29f32014-06-20 12:00:00 -0700999// checkForResumption returns true if we should perform resumption on this connection.
1000func (hs *serverHandshakeState) checkForResumption() bool {
1001 c := hs.c
1002
David Benjamin405da482016-08-08 17:25:07 -04001003 ticket := hs.clientHello.sessionTicket
1004 if len(ticket) == 0 && len(hs.clientHello.pskIdentities) > 0 && c.config.Bugs.AcceptAnySession {
1005 ticket = hs.clientHello.pskIdentities[0]
1006 }
1007 if len(ticket) > 0 {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001008 if c.config.SessionTicketsDisabled {
1009 return false
1010 }
David Benjaminb0c8db72014-09-24 15:19:56 -04001011
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001012 var ok bool
David Benjamin405da482016-08-08 17:25:07 -04001013 if hs.sessionState, ok = c.decryptTicket(ticket); !ok {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001014 return false
1015 }
1016 } else {
1017 if c.config.ServerSessionCache == nil {
1018 return false
1019 }
1020
1021 var ok bool
1022 sessionId := string(hs.clientHello.sessionId)
1023 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
1024 return false
1025 }
Adam Langley95c29f32014-06-20 12:00:00 -07001026 }
1027
David Benjamin405da482016-08-08 17:25:07 -04001028 if !c.config.Bugs.AcceptAnySession {
1029 // Never resume a session for a different SSL version.
1030 if c.vers != hs.sessionState.vers {
1031 return false
Adam Langley95c29f32014-06-20 12:00:00 -07001032 }
David Benjamin405da482016-08-08 17:25:07 -04001033
1034 cipherSuiteOk := false
1035 // Check that the client is still offering the ciphersuite in the session.
1036 for _, id := range hs.clientHello.cipherSuites {
1037 if id == hs.sessionState.cipherSuite {
1038 cipherSuiteOk = true
1039 break
1040 }
1041 }
1042 if !cipherSuiteOk {
1043 return false
1044 }
Adam Langley95c29f32014-06-20 12:00:00 -07001045 }
1046
1047 // Check that we also support the ciphersuite from the session.
Nick Harper728eed82016-07-07 17:36:52 -07001048 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 -07001049 if hs.suite == nil {
1050 return false
1051 }
1052
1053 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
1054 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
1055 if needClientCerts && !sessionHasClientCerts {
1056 return false
1057 }
1058 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
1059 return false
1060 }
1061
1062 return true
1063}
1064
1065func (hs *serverHandshakeState) doResumeHandshake() error {
1066 c := hs.c
1067
1068 hs.hello.cipherSuite = hs.suite.id
David Benjaminece3de92015-03-16 18:02:20 -04001069 if c.config.Bugs.SendCipherSuite != 0 {
1070 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
1071 }
Adam Langley95c29f32014-06-20 12:00:00 -07001072 // We echo the client's session ID in the ServerHello to let it know
1073 // that we're doing a resumption.
1074 hs.hello.sessionId = hs.clientHello.sessionId
Nick Harperb3d51be2016-07-01 11:43:18 -04001075 hs.hello.extensions.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -07001076
David Benjamin80d1b352016-05-04 19:19:06 -04001077 if c.config.Bugs.SendSCTListOnResume != nil {
Nick Harperb3d51be2016-07-01 11:43:18 -04001078 hs.hello.extensions.sctList = c.config.Bugs.SendSCTListOnResume
David Benjamin80d1b352016-05-04 19:19:06 -04001079 }
1080
Adam Langley95c29f32014-06-20 12:00:00 -07001081 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -04001082 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -04001083 hs.writeClientHash(hs.clientHello.marshal())
1084 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001085
1086 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
1087
1088 if len(hs.sessionState.certificates) > 0 {
1089 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
1090 return err
1091 }
1092 }
1093
1094 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -07001095 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -07001096
1097 return nil
1098}
1099
1100func (hs *serverHandshakeState) doFullHandshake() error {
1101 config := hs.c.config
1102 c := hs.c
1103
David Benjamin48cae082014-10-27 01:06:24 -04001104 isPSK := hs.suite.flags&suitePSK != 0
1105 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001106 hs.hello.extensions.ocspStapling = true
Adam Langley95c29f32014-06-20 12:00:00 -07001107 }
1108
David Benjamin61f95272014-11-25 01:55:35 -05001109 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001110 hs.hello.extensions.sctList = hs.cert.SignedCertificateTimestampList
David Benjamin61f95272014-11-25 01:55:35 -05001111 }
1112
Nick Harperb3d51be2016-07-01 11:43:18 -04001113 hs.hello.extensions.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
Adam Langley95c29f32014-06-20 12:00:00 -07001114 hs.hello.cipherSuite = hs.suite.id
David Benjamin6095de82014-12-27 01:50:38 -05001115 if config.Bugs.SendCipherSuite != 0 {
1116 hs.hello.cipherSuite = config.Bugs.SendCipherSuite
1117 }
Nick Harperb3d51be2016-07-01 11:43:18 -04001118 c.extendedMasterSecret = hs.hello.extensions.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -07001119
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001120 // Generate a session ID if we're to save the session.
Nick Harperb3d51be2016-07-01 11:43:18 -04001121 if !hs.hello.extensions.ticketSupported && config.ServerSessionCache != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001122 hs.hello.sessionId = make([]byte, 32)
1123 if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
1124 c.sendAlert(alertInternalError)
1125 return errors.New("tls: short read from Rand: " + err.Error())
1126 }
1127 }
1128
Adam Langley95c29f32014-06-20 12:00:00 -07001129 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -04001130 hs.writeClientHash(hs.clientHello.marshal())
1131 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001132
1133 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
1134
David Benjamin48cae082014-10-27 01:06:24 -04001135 if !isPSK {
1136 certMsg := new(certificateMsg)
David Benjamin8923c0b2015-06-07 11:42:34 -04001137 if !config.Bugs.EmptyCertificateList {
1138 certMsg.certificates = hs.cert.Certificate
1139 }
David Benjamin48cae082014-10-27 01:06:24 -04001140 if !config.Bugs.UnauthenticatedECDH {
David Benjaminbcb2d912015-02-24 23:45:43 -05001141 certMsgBytes := certMsg.marshal()
David Benjaminbcb2d912015-02-24 23:45:43 -05001142 hs.writeServerHash(certMsgBytes)
1143 c.writeRecord(recordTypeHandshake, certMsgBytes)
David Benjamin48cae082014-10-27 01:06:24 -04001144 }
David Benjamin1c375dd2014-07-12 00:48:23 -04001145 }
Adam Langley95c29f32014-06-20 12:00:00 -07001146
Nick Harperb3d51be2016-07-01 11:43:18 -04001147 if hs.hello.extensions.ocspStapling && !c.config.Bugs.SkipCertificateStatus {
Adam Langley95c29f32014-06-20 12:00:00 -07001148 certStatus := new(certificateStatusMsg)
1149 certStatus.statusType = statusTypeOCSP
1150 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -04001151 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001152 c.writeRecord(recordTypeHandshake, certStatus.marshal())
1153 }
1154
1155 keyAgreement := hs.suite.ka(c.vers)
1156 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
1157 if err != nil {
1158 c.sendAlert(alertHandshakeFailure)
1159 return err
1160 }
Steven Valdez5440fe02016-07-18 12:40:30 -04001161 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
1162 c.curveID = ecdhe.curveID
1163 }
David Benjamin9c651c92014-07-12 13:27:45 -04001164 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -04001165 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001166 c.writeRecord(recordTypeHandshake, skx.marshal())
1167 }
1168
1169 if config.ClientAuth >= RequestClientCert {
1170 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -04001171 certReq := &certificateRequestMsg{
1172 certificateTypes: config.ClientCertificateTypes,
1173 }
1174 if certReq.certificateTypes == nil {
1175 certReq.certificateTypes = []byte{
1176 byte(CertTypeRSASign),
1177 byte(CertTypeECDSASign),
1178 }
Adam Langley95c29f32014-06-20 12:00:00 -07001179 }
1180 if c.vers >= VersionTLS12 {
Nick Harper60edffd2016-06-21 15:19:24 -07001181 certReq.hasSignatureAlgorithm = true
1182 if !config.Bugs.NoSignatureAlgorithms {
David Benjamin7a41d372016-07-09 11:21:54 -07001183 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin000800a2014-11-14 01:43:59 -05001184 }
Adam Langley95c29f32014-06-20 12:00:00 -07001185 }
1186
1187 // An empty list of certificateAuthorities signals to
1188 // the client that it may send any certificate in response
1189 // to our request. When we know the CAs we trust, then
1190 // we can send them down, so that the client can choose
1191 // an appropriate certificate to give to us.
1192 if config.ClientCAs != nil {
1193 certReq.certificateAuthorities = config.ClientCAs.Subjects()
1194 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001195 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001196 c.writeRecord(recordTypeHandshake, certReq.marshal())
1197 }
1198
1199 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001200 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001201 c.writeRecord(recordTypeHandshake, helloDone.marshal())
David Benjamin582ba042016-07-07 12:33:25 -07001202 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001203
1204 var pub crypto.PublicKey // public key for client auth, if any
1205
David Benjamin83f90402015-01-27 01:09:43 -05001206 if err := c.simulatePacketLoss(nil); err != nil {
1207 return err
1208 }
Adam Langley95c29f32014-06-20 12:00:00 -07001209 msg, err := c.readHandshake()
1210 if err != nil {
1211 return err
1212 }
1213
1214 var ok bool
1215 // If we requested a client certificate, then the client must send a
1216 // certificate message, even if it's empty.
1217 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -04001218 var certMsg *certificateMsg
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001219 var certificates [][]byte
1220 if certMsg, ok = msg.(*certificateMsg); ok {
1221 if c.vers == VersionSSL30 && len(certMsg.certificates) == 0 {
1222 return errors.New("tls: empty certificate message in SSL 3.0")
1223 }
1224
1225 hs.writeClientHash(certMsg.marshal())
1226 certificates = certMsg.certificates
1227 } else if c.vers != VersionSSL30 {
1228 // In TLS, the Certificate message is required. In SSL
1229 // 3.0, the peer skips it when sending no certificates.
Adam Langley95c29f32014-06-20 12:00:00 -07001230 c.sendAlert(alertUnexpectedMessage)
1231 return unexpectedMessageError(certMsg, msg)
1232 }
Adam Langley95c29f32014-06-20 12:00:00 -07001233
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001234 if len(certificates) == 0 {
Adam Langley95c29f32014-06-20 12:00:00 -07001235 // The client didn't actually send a certificate
1236 switch config.ClientAuth {
1237 case RequireAnyClientCert, RequireAndVerifyClientCert:
1238 c.sendAlert(alertBadCertificate)
1239 return errors.New("tls: client didn't provide a certificate")
1240 }
1241 }
1242
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001243 pub, err = hs.processCertsFromClient(certificates)
Adam Langley95c29f32014-06-20 12:00:00 -07001244 if err != nil {
1245 return err
1246 }
1247
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001248 if ok {
1249 msg, err = c.readHandshake()
1250 if err != nil {
1251 return err
1252 }
Adam Langley95c29f32014-06-20 12:00:00 -07001253 }
1254 }
1255
1256 // Get client key exchange
1257 ckx, ok := msg.(*clientKeyExchangeMsg)
1258 if !ok {
1259 c.sendAlert(alertUnexpectedMessage)
1260 return unexpectedMessageError(ckx, msg)
1261 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001262 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001263
David Benjamine098ec22014-08-27 23:13:20 -04001264 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
1265 if err != nil {
1266 c.sendAlert(alertHandshakeFailure)
1267 return err
1268 }
Adam Langley75712922014-10-10 16:23:43 -07001269 if c.extendedMasterSecret {
1270 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1271 } else {
1272 if c.config.Bugs.RequireExtendedMasterSecret {
1273 return errors.New("tls: extended master secret required but not supported by peer")
1274 }
1275 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
1276 }
David Benjamine098ec22014-08-27 23:13:20 -04001277
Adam Langley95c29f32014-06-20 12:00:00 -07001278 // If we received a client cert in response to our certificate request message,
1279 // the client will send us a certificateVerifyMsg immediately after the
1280 // clientKeyExchangeMsg. This message is a digest of all preceding
1281 // handshake-layer messages that is signed using the private key corresponding
1282 // to the client's certificate. This allows us to verify that the client is in
1283 // possession of the private key of the certificate.
1284 if len(c.peerCertificates) > 0 {
1285 msg, err = c.readHandshake()
1286 if err != nil {
1287 return err
1288 }
1289 certVerify, ok := msg.(*certificateVerifyMsg)
1290 if !ok {
1291 c.sendAlert(alertUnexpectedMessage)
1292 return unexpectedMessageError(certVerify, msg)
1293 }
1294
David Benjaminde620d92014-07-18 15:03:41 -04001295 // Determine the signature type.
Nick Harper60edffd2016-06-21 15:19:24 -07001296 var sigAlg signatureAlgorithm
1297 if certVerify.hasSignatureAlgorithm {
1298 sigAlg = certVerify.signatureAlgorithm
Nick Harper60edffd2016-06-21 15:19:24 -07001299 c.peerSignatureAlgorithm = sigAlg
David Benjaminde620d92014-07-18 15:03:41 -04001300 }
1301
Nick Harper60edffd2016-06-21 15:19:24 -07001302 if c.vers > VersionSSL30 {
David Benjamin1fb125c2016-07-08 18:52:12 -07001303 err = verifyMessage(c.vers, pub, c.config, sigAlg, hs.finishedHash.buffer, certVerify.signature)
Nick Harper60edffd2016-06-21 15:19:24 -07001304 } else {
1305 // SSL 3.0's client certificate construction is
1306 // incompatible with signatureAlgorithm.
1307 rsaPub, ok := pub.(*rsa.PublicKey)
1308 if !ok {
1309 err = errors.New("unsupported key type for client certificate")
1310 } else {
1311 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
1312 err = rsa.VerifyPKCS1v15(rsaPub, crypto.MD5SHA1, digest, certVerify.signature)
David Benjaminde620d92014-07-18 15:03:41 -04001313 }
Adam Langley95c29f32014-06-20 12:00:00 -07001314 }
1315 if err != nil {
1316 c.sendAlert(alertBadCertificate)
1317 return errors.New("could not validate signature of connection nonces: " + err.Error())
1318 }
1319
David Benjamin83c0bc92014-08-04 01:23:53 -04001320 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001321 }
1322
David Benjamine098ec22014-08-27 23:13:20 -04001323 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001324
1325 return nil
1326}
1327
1328func (hs *serverHandshakeState) establishKeys() error {
1329 c := hs.c
1330
1331 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001332 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 -07001333
1334 var clientCipher, serverCipher interface{}
1335 var clientHash, serverHash macFunction
1336
1337 if hs.suite.aead == nil {
1338 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
1339 clientHash = hs.suite.mac(c.vers, clientMAC)
1340 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
1341 serverHash = hs.suite.mac(c.vers, serverMAC)
1342 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001343 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1344 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001345 }
1346
1347 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
1348 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
1349
1350 return nil
1351}
1352
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001353func (hs *serverHandshakeState) readFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001354 c := hs.c
1355
1356 c.readRecord(recordTypeChangeCipherSpec)
1357 if err := c.in.error(); err != nil {
1358 return err
1359 }
1360
Nick Harperb3d51be2016-07-01 11:43:18 -04001361 if hs.hello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001362 msg, err := c.readHandshake()
1363 if err != nil {
1364 return err
1365 }
1366 nextProto, ok := msg.(*nextProtoMsg)
1367 if !ok {
1368 c.sendAlert(alertUnexpectedMessage)
1369 return unexpectedMessageError(nextProto, msg)
1370 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001371 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001372 c.clientProtocol = nextProto.proto
1373 }
1374
Nick Harperb3d51be2016-07-01 11:43:18 -04001375 if hs.hello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001376 msg, err := c.readHandshake()
1377 if err != nil {
1378 return err
1379 }
David Benjamin24599a82016-06-30 18:56:53 -04001380 channelIDMsg, ok := msg.(*channelIDMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001381 if !ok {
1382 c.sendAlert(alertUnexpectedMessage)
David Benjamin24599a82016-06-30 18:56:53 -04001383 return unexpectedMessageError(channelIDMsg, msg)
David Benjamind30a9902014-08-24 01:44:23 -04001384 }
David Benjamin24599a82016-06-30 18:56:53 -04001385 x := new(big.Int).SetBytes(channelIDMsg.channelID[0:32])
1386 y := new(big.Int).SetBytes(channelIDMsg.channelID[32:64])
1387 r := new(big.Int).SetBytes(channelIDMsg.channelID[64:96])
1388 s := new(big.Int).SetBytes(channelIDMsg.channelID[96:128])
David Benjamind30a9902014-08-24 01:44:23 -04001389 if !elliptic.P256().IsOnCurve(x, y) {
1390 return errors.New("tls: invalid channel ID public key")
1391 }
1392 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
1393 var resumeHash []byte
1394 if isResume {
1395 resumeHash = hs.sessionState.handshakeHash
1396 }
1397 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
1398 return errors.New("tls: invalid channel ID signature")
1399 }
1400 c.channelID = channelID
1401
David Benjamin24599a82016-06-30 18:56:53 -04001402 hs.writeClientHash(channelIDMsg.marshal())
David Benjamind30a9902014-08-24 01:44:23 -04001403 }
1404
Adam Langley95c29f32014-06-20 12:00:00 -07001405 msg, err := c.readHandshake()
1406 if err != nil {
1407 return err
1408 }
1409 clientFinished, ok := msg.(*finishedMsg)
1410 if !ok {
1411 c.sendAlert(alertUnexpectedMessage)
1412 return unexpectedMessageError(clientFinished, msg)
1413 }
1414
1415 verify := hs.finishedHash.clientSum(hs.masterSecret)
1416 if len(verify) != len(clientFinished.verifyData) ||
1417 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
1418 c.sendAlert(alertHandshakeFailure)
1419 return errors.New("tls: client's Finished message is incorrect")
1420 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001421 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001422 copy(out, clientFinished.verifyData)
Adam Langley95c29f32014-06-20 12:00:00 -07001423
David Benjamin83c0bc92014-08-04 01:23:53 -04001424 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001425 return nil
1426}
1427
1428func (hs *serverHandshakeState) sendSessionTicket() error {
Adam Langley95c29f32014-06-20 12:00:00 -07001429 c := hs.c
Adam Langley95c29f32014-06-20 12:00:00 -07001430 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -04001431 vers: c.vers,
1432 cipherSuite: hs.suite.id,
1433 masterSecret: hs.masterSecret,
1434 certificates: hs.certsFromClient,
1435 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -07001436 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001437
Nick Harperb3d51be2016-07-01 11:43:18 -04001438 if !hs.hello.extensions.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001439 if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
1440 c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
1441 }
1442 return nil
1443 }
1444
1445 m := new(newSessionTicketMsg)
1446
David Benjamindd6fed92015-10-23 17:41:12 -04001447 if !c.config.Bugs.SendEmptySessionTicket {
1448 var err error
1449 m.ticket, err = c.encryptTicket(&state)
1450 if err != nil {
1451 return err
1452 }
Adam Langley95c29f32014-06-20 12:00:00 -07001453 }
Adam Langley95c29f32014-06-20 12:00:00 -07001454
David Benjamin83c0bc92014-08-04 01:23:53 -04001455 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001456 c.writeRecord(recordTypeHandshake, m.marshal())
1457
1458 return nil
1459}
1460
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001461func (hs *serverHandshakeState) sendFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001462 c := hs.c
1463
David Benjamin86271ee2014-07-21 16:14:03 -04001464 finished := new(finishedMsg)
1465 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001466 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001467 if c.config.Bugs.BadFinished {
1468 finished.verifyData[0]++
1469 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001470 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001471 hs.finishedBytes = finished.marshal()
1472 hs.writeServerHash(hs.finishedBytes)
1473 postCCSBytes := hs.finishedBytes
David Benjamin86271ee2014-07-21 16:14:03 -04001474
1475 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
1476 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
1477 postCCSBytes = postCCSBytes[5:]
David Benjamin61672812016-07-14 23:10:43 -04001478 } else if c.config.Bugs.SendUnencryptedFinished {
1479 c.writeRecord(recordTypeHandshake, postCCSBytes)
1480 postCCSBytes = nil
David Benjamin86271ee2014-07-21 16:14:03 -04001481 }
David Benjamin582ba042016-07-07 12:33:25 -07001482 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001483
David Benjamina0e52232014-07-19 17:39:58 -04001484 if !c.config.Bugs.SkipChangeCipherSpec {
David Benjamin8411b242015-11-26 12:07:28 -05001485 ccs := []byte{1}
1486 if c.config.Bugs.BadChangeCipherSpec != nil {
1487 ccs = c.config.Bugs.BadChangeCipherSpec
1488 }
1489 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamina0e52232014-07-19 17:39:58 -04001490 }
Adam Langley95c29f32014-06-20 12:00:00 -07001491
David Benjamin4189bd92015-01-25 23:52:39 -05001492 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1493 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1494 }
David Benjamindc3da932015-03-12 15:09:02 -04001495 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1496 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1497 return errors.New("tls: simulating post-CCS alert")
1498 }
David Benjamin4189bd92015-01-25 23:52:39 -05001499
David Benjamin61672812016-07-14 23:10:43 -04001500 if !c.config.Bugs.SkipFinished && len(postCCSBytes) > 0 {
David Benjaminb80168e2015-02-08 18:30:14 -05001501 c.writeRecord(recordTypeHandshake, postCCSBytes)
David Benjamin02edcd02016-07-27 17:40:37 -04001502 if c.config.Bugs.SendExtraFinished {
1503 c.writeRecord(recordTypeHandshake, finished.marshal())
1504 }
1505
David Benjamin12d2c482016-07-24 10:56:51 -04001506 if !c.config.Bugs.PackHelloRequestWithFinished {
1507 // Defer flushing until renegotiation.
1508 c.flushHandshake()
1509 }
David Benjaminb3774b92015-01-31 17:16:01 -05001510 }
Adam Langley95c29f32014-06-20 12:00:00 -07001511
David Benjaminc565ebb2015-04-03 04:06:36 -04001512 c.cipherSuite = hs.suite
Adam Langley95c29f32014-06-20 12:00:00 -07001513
1514 return nil
1515}
1516
1517// processCertsFromClient takes a chain of client certificates either from a
1518// Certificates message or from a sessionState and verifies them. It returns
1519// the public key of the leaf certificate.
1520func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
1521 c := hs.c
1522
1523 hs.certsFromClient = certificates
1524 certs := make([]*x509.Certificate, len(certificates))
1525 var err error
1526 for i, asn1Data := range certificates {
1527 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
1528 c.sendAlert(alertBadCertificate)
1529 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
1530 }
1531 }
1532
1533 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
1534 opts := x509.VerifyOptions{
1535 Roots: c.config.ClientCAs,
1536 CurrentTime: c.config.time(),
1537 Intermediates: x509.NewCertPool(),
1538 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
1539 }
1540
1541 for _, cert := range certs[1:] {
1542 opts.Intermediates.AddCert(cert)
1543 }
1544
1545 chains, err := certs[0].Verify(opts)
1546 if err != nil {
1547 c.sendAlert(alertBadCertificate)
1548 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
1549 }
1550
1551 ok := false
1552 for _, ku := range certs[0].ExtKeyUsage {
1553 if ku == x509.ExtKeyUsageClientAuth {
1554 ok = true
1555 break
1556 }
1557 }
1558 if !ok {
1559 c.sendAlert(alertHandshakeFailure)
1560 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
1561 }
1562
1563 c.verifiedChains = chains
1564 }
1565
1566 if len(certs) > 0 {
1567 var pub crypto.PublicKey
1568 switch key := certs[0].PublicKey.(type) {
1569 case *ecdsa.PublicKey, *rsa.PublicKey:
1570 pub = key
1571 default:
1572 c.sendAlert(alertUnsupportedCertificate)
1573 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
1574 }
1575 c.peerCertificates = certs
1576 return pub, nil
1577 }
1578
1579 return nil, nil
1580}
1581
David Benjamin83c0bc92014-08-04 01:23:53 -04001582func (hs *serverHandshakeState) writeServerHash(msg []byte) {
1583 // writeServerHash is called before writeRecord.
1584 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1585}
1586
1587func (hs *serverHandshakeState) writeClientHash(msg []byte) {
1588 // writeClientHash is called after readHandshake.
1589 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1590}
1591
1592func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
1593 if hs.c.isDTLS {
1594 // This is somewhat hacky. DTLS hashes a slightly different format.
1595 // First, the TLS header.
1596 hs.finishedHash.Write(msg[:4])
1597 // Then the sequence number and reassembled fragment offset (always 0).
1598 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1599 // Then the reassembled fragment (always equal to the message length).
1600 hs.finishedHash.Write(msg[1:4])
1601 // And then the message body.
1602 hs.finishedHash.Write(msg[4:])
1603 } else {
1604 hs.finishedHash.Write(msg)
1605 }
1606}
1607
Adam Langley95c29f32014-06-20 12:00:00 -07001608// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
1609// is acceptable to use.
Nick Harper728eed82016-07-07 17:36:52 -07001610func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk, pskOk bool) *cipherSuite {
Adam Langley95c29f32014-06-20 12:00:00 -07001611 for _, supported := range supportedCipherSuites {
1612 if id == supported {
1613 var candidate *cipherSuite
1614
1615 for _, s := range cipherSuites {
1616 if s.id == id {
1617 candidate = s
1618 break
1619 }
1620 }
1621 if candidate == nil {
1622 continue
1623 }
1624 // Don't select a ciphersuite which we can't
1625 // support for this client.
David Benjamin0407e762016-06-17 16:41:18 -04001626 if !c.config.Bugs.EnableAllCiphers {
Nick Harper728eed82016-07-07 17:36:52 -07001627 if (candidate.flags&suitePSK != 0) && !pskOk {
1628 continue
1629 }
David Benjamin0407e762016-06-17 16:41:18 -04001630 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
1631 continue
1632 }
1633 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
1634 continue
1635 }
1636 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
1637 continue
1638 }
Nick Harper728eed82016-07-07 17:36:52 -07001639 if version >= VersionTLS13 && candidate.flags&suiteTLS13 == 0 {
1640 continue
1641 }
David Benjamin0407e762016-06-17 16:41:18 -04001642 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
1643 continue
1644 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001645 }
Adam Langley95c29f32014-06-20 12:00:00 -07001646 return candidate
1647 }
1648 }
1649
1650 return nil
1651}
David Benjaminf93995b2015-11-05 18:23:20 -05001652
1653func isTLS12Cipher(id uint16) bool {
1654 for _, cipher := range cipherSuites {
1655 if cipher.id != id {
1656 continue
1657 }
1658 return cipher.flags&suiteTLS12 != 0
1659 }
1660 // Unknown cipher.
1661 return false
1662}