blob: 29f36bb1c902c35d9dbf771e22db86ad5c2f26f9 [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
David Benjamin46662482016-08-17 00:51:00 -0400353 // Check the cipher is enabled by the server or is a resumption
354 // suite of one enabled by the server. Account for the cipher
355 // change on resume.
356 //
357 // TODO(davidben): The ecdhePSKSuite mess will be gone with the
358 // new cipher negotiation scheme.
Nick Harper0b3625b2016-07-25 16:16:28 -0700359 var found bool
360 for _, id := range config.cipherSuites() {
David Benjamin46662482016-08-17 00:51:00 -0400361 if ecdhePSKSuite(id) == suiteId {
Nick Harper0b3625b2016-07-25 16:16:28 -0700362 found = true
363 break
364 }
365 }
David Benjamin405da482016-08-08 17:25:07 -0400366
Nick Harper0b3625b2016-07-25 16:16:28 -0700367 if suite != nil && found {
368 hs.sessionState = sessionState
369 hs.suite = suite
370 hs.hello.hasPSKIdentity = true
371 hs.hello.pskIdentity = uint16(i)
372 c.didResume = true
373 break
374 }
Nick Harper728eed82016-07-07 17:36:52 -0700375 }
376
Nick Harper0b3625b2016-07-25 16:16:28 -0700377 // If not resuming, select the cipher suite.
378 if hs.suite == nil {
379 var preferenceList, supportedList []uint16
380 if config.PreferServerCipherSuites {
381 preferenceList = config.cipherSuites()
382 supportedList = hs.clientHello.cipherSuites
383 } else {
384 preferenceList = hs.clientHello.cipherSuites
385 supportedList = config.cipherSuites()
386 }
387
388 for _, id := range preferenceList {
389 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, supportedCurve, ecdsaOk, false); hs.suite != nil {
390 break
391 }
Nick Harper728eed82016-07-07 17:36:52 -0700392 }
393 }
394
395 if hs.suite == nil {
396 c.sendAlert(alertHandshakeFailure)
397 return errors.New("tls: no cipher suite supported by both client and server")
398 }
399
400 hs.hello.cipherSuite = hs.suite.id
Steven Valdez0ee2e112016-07-15 06:51:15 -0400401 if c.config.Bugs.SendCipherSuite != 0 {
402 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
403 }
404
Nick Harper728eed82016-07-07 17:36:52 -0700405 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
406 hs.finishedHash.discardHandshakeBuffer()
407 hs.writeClientHash(hs.clientHello.marshal())
408
409 // Resolve PSK and compute the early secret.
Nick Harper0b3625b2016-07-25 16:16:28 -0700410 var psk []byte
411 // The only way for hs.suite to be a PSK suite yet for there to be
412 // no sessionState is if config.Bugs.EnableAllCiphers is true and
413 // the test runner forced us to negotiated a PSK suite. It doesn't
414 // really matter what we do here so long as we continue the
415 // handshake and let the client error out.
416 if hs.suite.flags&suitePSK != 0 && hs.sessionState != nil {
417 psk = deriveResumptionPSK(hs.suite, hs.sessionState.masterSecret)
418 hs.finishedHash.setResumptionContext(deriveResumptionContext(hs.suite, hs.sessionState.masterSecret))
419 } else {
420 psk = hs.finishedHash.zeroSecret()
421 hs.finishedHash.setResumptionContext(hs.finishedHash.zeroSecret())
422 }
Nick Harper728eed82016-07-07 17:36:52 -0700423
424 earlySecret := hs.finishedHash.extractKey(hs.finishedHash.zeroSecret(), psk)
425
426 // Resolve ECDHE and compute the handshake secret.
427 var ecdheSecret []byte
Steven Valdez143e8b32016-07-11 13:19:03 -0400428 if hs.suite.flags&suiteECDHE != 0 && !config.Bugs.MissingKeyShare {
Nick Harper728eed82016-07-07 17:36:52 -0700429 // Look for the key share corresponding to our selected curve.
430 var selectedKeyShare *keyShareEntry
431 for i := range hs.clientHello.keyShares {
432 if hs.clientHello.keyShares[i].group == selectedCurve {
433 selectedKeyShare = &hs.clientHello.keyShares[i]
434 break
435 }
436 }
437
David Benjamine73c7f42016-08-17 00:29:33 -0400438 if config.Bugs.ExpectMissingKeyShare && selectedKeyShare != nil {
439 return errors.New("tls: expected missing key share")
440 }
441
Steven Valdez5440fe02016-07-18 12:40:30 -0400442 sendHelloRetryRequest := selectedKeyShare == nil
443 if config.Bugs.UnnecessaryHelloRetryRequest {
444 sendHelloRetryRequest = true
445 }
446 if config.Bugs.SkipHelloRetryRequest {
447 sendHelloRetryRequest = false
448 }
449 if sendHelloRetryRequest {
450 firstTime := true
451 ResendHelloRetryRequest:
Nick Harperdcfbc672016-07-16 17:47:31 +0200452 // Send HelloRetryRequest.
453 helloRetryRequestMsg := helloRetryRequestMsg{
454 vers: c.vers,
455 cipherSuite: hs.hello.cipherSuite,
456 selectedGroup: selectedCurve,
457 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400458 if config.Bugs.SendHelloRetryRequestCurve != 0 {
459 helloRetryRequestMsg.selectedGroup = config.Bugs.SendHelloRetryRequestCurve
460 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200461 hs.writeServerHash(helloRetryRequestMsg.marshal())
462 c.writeRecord(recordTypeHandshake, helloRetryRequestMsg.marshal())
David Benjamine73c7f42016-08-17 00:29:33 -0400463 c.flushHandshake()
Nick Harperdcfbc672016-07-16 17:47:31 +0200464
465 // Read new ClientHello.
466 newMsg, err := c.readHandshake()
467 if err != nil {
468 return err
469 }
470 newClientHello, ok := newMsg.(*clientHelloMsg)
471 if !ok {
472 c.sendAlert(alertUnexpectedMessage)
473 return unexpectedMessageError(newClientHello, newMsg)
474 }
475 hs.writeClientHash(newClientHello.marshal())
476
477 // Check that the new ClientHello matches the old ClientHello, except for
478 // the addition of the new KeyShareEntry at the end of the list, and
479 // removing the EarlyDataIndication extension (if present).
480 newKeyShares := newClientHello.keyShares
481 if len(newKeyShares) == 0 || newKeyShares[len(newKeyShares)-1].group != selectedCurve {
482 return errors.New("tls: KeyShare from HelloRetryRequest not present in new ClientHello")
483 }
484 oldClientHelloCopy := *hs.clientHello
485 oldClientHelloCopy.raw = nil
486 oldClientHelloCopy.hasEarlyData = false
487 oldClientHelloCopy.earlyDataContext = nil
488 newClientHelloCopy := *newClientHello
489 newClientHelloCopy.raw = nil
490 newClientHelloCopy.keyShares = newKeyShares[:len(newKeyShares)-1]
491 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
492 return errors.New("tls: new ClientHello does not match")
493 }
494
Steven Valdez5440fe02016-07-18 12:40:30 -0400495 if firstTime && config.Bugs.SecondHelloRetryRequest {
496 firstTime = false
497 goto ResendHelloRetryRequest
498 }
499
Nick Harperdcfbc672016-07-16 17:47:31 +0200500 selectedKeyShare = &newKeyShares[len(newKeyShares)-1]
Nick Harper728eed82016-07-07 17:36:52 -0700501 }
502
503 // Once a curve has been selected and a key share identified,
504 // the server needs to generate a public value and send it in
505 // the ServerHello.
Steven Valdez5440fe02016-07-18 12:40:30 -0400506 curve, ok := curveForCurveID(selectedCurve)
Nick Harper728eed82016-07-07 17:36:52 -0700507 if !ok {
508 panic("tls: server failed to look up curve ID")
509 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400510 c.curveID = selectedCurve
511
512 var peerKey []byte
513 if config.Bugs.SkipHelloRetryRequest {
514 // If skipping HelloRetryRequest, use a random key to
515 // avoid crashing.
516 curve2, _ := curveForCurveID(selectedCurve)
517 var err error
518 peerKey, err = curve2.offer(config.rand())
519 if err != nil {
520 return err
521 }
522 } else {
523 peerKey = selectedKeyShare.keyExchange
524 }
525
Nick Harper728eed82016-07-07 17:36:52 -0700526 var publicKey []byte
527 var err error
Steven Valdez5440fe02016-07-18 12:40:30 -0400528 publicKey, ecdheSecret, err = curve.accept(config.rand(), peerKey)
Nick Harper728eed82016-07-07 17:36:52 -0700529 if err != nil {
530 c.sendAlert(alertHandshakeFailure)
531 return err
532 }
533 hs.hello.hasKeyShare = true
Steven Valdez0ee2e112016-07-15 06:51:15 -0400534
Steven Valdez5440fe02016-07-18 12:40:30 -0400535 curveID := selectedCurve
Steven Valdez0ee2e112016-07-15 06:51:15 -0400536 if c.config.Bugs.SendCurve != 0 {
537 curveID = config.Bugs.SendCurve
538 }
539 if c.config.Bugs.InvalidECDHPoint {
540 publicKey[0] ^= 0xff
541 }
542
Nick Harper728eed82016-07-07 17:36:52 -0700543 hs.hello.keyShare = keyShareEntry{
Steven Valdez0ee2e112016-07-15 06:51:15 -0400544 group: curveID,
Nick Harper728eed82016-07-07 17:36:52 -0700545 keyExchange: publicKey,
546 }
Steven Valdez143e8b32016-07-11 13:19:03 -0400547
548 if config.Bugs.EncryptedExtensionsWithKeyShare {
549 encryptedExtensions.extensions.hasKeyShare = true
550 encryptedExtensions.extensions.keyShare = keyShareEntry{
551 group: curveID,
552 keyExchange: publicKey,
553 }
554 }
Nick Harper728eed82016-07-07 17:36:52 -0700555 } else {
556 ecdheSecret = hs.finishedHash.zeroSecret()
557 }
558
559 // Send unencrypted ServerHello.
560 hs.writeServerHash(hs.hello.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400561 if config.Bugs.PartialEncryptedExtensionsWithServerHello {
562 helloBytes := hs.hello.marshal()
563 toWrite := make([]byte, 0, len(helloBytes)+1)
564 toWrite = append(toWrite, helloBytes...)
565 toWrite = append(toWrite, typeEncryptedExtensions)
566 c.writeRecord(recordTypeHandshake, toWrite)
567 } else {
568 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
569 }
Nick Harper728eed82016-07-07 17:36:52 -0700570 c.flushHandshake()
571
572 // Compute the handshake secret.
573 handshakeSecret := hs.finishedHash.extractKey(earlySecret, ecdheSecret)
574
575 // Switch to handshake traffic keys.
576 handshakeTrafficSecret := hs.finishedHash.deriveSecret(handshakeSecret, handshakeTrafficLabel)
David Benjamin21c00282016-07-18 21:56:23 +0200577 c.out.useTrafficSecret(c.vers, hs.suite, handshakeTrafficSecret, handshakePhase, serverWrite)
578 c.in.useTrafficSecret(c.vers, hs.suite, handshakeTrafficSecret, handshakePhase, clientWrite)
Nick Harper728eed82016-07-07 17:36:52 -0700579
Nick Harper0b3625b2016-07-25 16:16:28 -0700580 if hs.suite.flags&suitePSK == 0 {
David Benjamin615119a2016-07-06 19:22:55 -0700581 if hs.clientHello.ocspStapling {
582 encryptedExtensions.extensions.ocspResponse = hs.cert.OCSPStaple
583 }
584 if hs.clientHello.sctListSupported {
585 encryptedExtensions.extensions.sctList = hs.cert.SignedCertificateTimestampList
586 }
587 }
588
Nick Harper728eed82016-07-07 17:36:52 -0700589 // Send EncryptedExtensions.
590 hs.writeServerHash(encryptedExtensions.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400591 if config.Bugs.PartialEncryptedExtensionsWithServerHello {
592 // The first byte has already been sent.
593 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()[1:])
594 } else {
595 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal())
596 }
Nick Harper728eed82016-07-07 17:36:52 -0700597
598 if hs.suite.flags&suitePSK == 0 {
599 if config.ClientAuth >= RequestClientCert {
David Benjamin8d343b42016-07-09 14:26:01 -0700600 // Request a client certificate
601 certReq := &certificateRequestMsg{
602 hasSignatureAlgorithm: true,
603 hasRequestContext: true,
David Benjamin8a8349b2016-08-18 02:32:23 -0400604 requestContext: config.Bugs.SendRequestContext,
David Benjamin8d343b42016-07-09 14:26:01 -0700605 }
606 if !config.Bugs.NoSignatureAlgorithms {
David Benjaminf74ec792016-07-13 21:18:49 -0400607 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin8d343b42016-07-09 14:26:01 -0700608 }
609
610 // An empty list of certificateAuthorities signals to
611 // the client that it may send any certificate in response
612 // to our request. When we know the CAs we trust, then
613 // we can send them down, so that the client can choose
614 // an appropriate certificate to give to us.
615 if config.ClientCAs != nil {
616 certReq.certificateAuthorities = config.ClientCAs.Subjects()
617 }
618 hs.writeServerHash(certReq.marshal())
619 c.writeRecord(recordTypeHandshake, certReq.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700620 }
621
622 certMsg := &certificateMsg{
623 hasRequestContext: true,
624 }
625 if !config.Bugs.EmptyCertificateList {
626 certMsg.certificates = hs.cert.Certificate
627 }
David Benjamin1edae6b2016-07-13 16:58:23 -0400628 certMsgBytes := certMsg.marshal()
David Benjamin1edae6b2016-07-13 16:58:23 -0400629 hs.writeServerHash(certMsgBytes)
630 c.writeRecord(recordTypeHandshake, certMsgBytes)
Nick Harper728eed82016-07-07 17:36:52 -0700631
632 certVerify := &certificateVerifyMsg{
633 hasSignatureAlgorithm: true,
634 }
635
636 // Determine the hash to sign.
637 privKey := hs.cert.PrivateKey
638
639 var err error
640 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, config, hs.clientHello.signatureAlgorithms)
641 if err != nil {
642 c.sendAlert(alertInternalError)
643 return err
644 }
645
646 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
647 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
648 if err != nil {
649 c.sendAlert(alertInternalError)
650 return err
651 }
652
Steven Valdez0ee2e112016-07-15 06:51:15 -0400653 if config.Bugs.SendSignatureAlgorithm != 0 {
654 certVerify.signatureAlgorithm = config.Bugs.SendSignatureAlgorithm
655 }
656
Nick Harper728eed82016-07-07 17:36:52 -0700657 hs.writeServerHash(certVerify.marshal())
658 c.writeRecord(recordTypeHandshake, certVerify.marshal())
Nick Harper0b3625b2016-07-25 16:16:28 -0700659 } else {
660 // Pick up certificates from the session instead.
661 // hs.sessionState may be nil if config.Bugs.EnableAllCiphers is
662 // true.
663 if hs.sessionState != nil && len(hs.sessionState.certificates) > 0 {
664 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
665 return err
666 }
667 }
Nick Harper728eed82016-07-07 17:36:52 -0700668 }
669
670 finished := new(finishedMsg)
671 finished.verifyData = hs.finishedHash.serverSum(handshakeTrafficSecret)
672 if config.Bugs.BadFinished {
673 finished.verifyData[0]++
674 }
675 hs.writeServerHash(finished.marshal())
676 c.writeRecord(recordTypeHandshake, finished.marshal())
David Benjamin02edcd02016-07-27 17:40:37 -0400677 if c.config.Bugs.SendExtraFinished {
678 c.writeRecord(recordTypeHandshake, finished.marshal())
679 }
Nick Harper728eed82016-07-07 17:36:52 -0700680 c.flushHandshake()
681
682 // The various secrets do not incorporate the client's final leg, so
683 // derive them now before updating the handshake context.
684 masterSecret := hs.finishedHash.extractKey(handshakeSecret, hs.finishedHash.zeroSecret())
685 trafficSecret := hs.finishedHash.deriveSecret(masterSecret, applicationTrafficLabel)
686
David Benjamin2aad4062016-07-14 23:15:40 -0400687 // Switch to application data keys on write. In particular, any alerts
688 // from the client certificate are sent over these keys.
David Benjamin21c00282016-07-18 21:56:23 +0200689 c.out.useTrafficSecret(c.vers, hs.suite, trafficSecret, applicationPhase, serverWrite)
David Benjamin2aad4062016-07-14 23:15:40 -0400690
Nick Harper728eed82016-07-07 17:36:52 -0700691 // If we requested a client certificate, then the client must send a
692 // certificate message, even if it's empty.
693 if config.ClientAuth >= RequestClientCert {
David Benjamin8d343b42016-07-09 14:26:01 -0700694 msg, err := c.readHandshake()
695 if err != nil {
696 return err
697 }
698
699 certMsg, ok := msg.(*certificateMsg)
700 if !ok {
701 c.sendAlert(alertUnexpectedMessage)
702 return unexpectedMessageError(certMsg, msg)
703 }
704 hs.writeClientHash(certMsg.marshal())
705
706 if len(certMsg.certificates) == 0 {
707 // The client didn't actually send a certificate
708 switch config.ClientAuth {
709 case RequireAnyClientCert, RequireAndVerifyClientCert:
710 c.sendAlert(alertBadCertificate)
711 return errors.New("tls: client didn't provide a certificate")
712 }
713 }
714
715 pub, err := hs.processCertsFromClient(certMsg.certificates)
716 if err != nil {
717 return err
718 }
719
720 if len(c.peerCertificates) > 0 {
721 msg, err = c.readHandshake()
722 if err != nil {
723 return err
724 }
725
726 certVerify, ok := msg.(*certificateVerifyMsg)
727 if !ok {
728 c.sendAlert(alertUnexpectedMessage)
729 return unexpectedMessageError(certVerify, msg)
730 }
731
David Benjaminf74ec792016-07-13 21:18:49 -0400732 c.peerSignatureAlgorithm = certVerify.signatureAlgorithm
David Benjamin8d343b42016-07-09 14:26:01 -0700733 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
734 if err := verifyMessage(c.vers, pub, config, certVerify.signatureAlgorithm, input, certVerify.signature); err != nil {
735 c.sendAlert(alertBadCertificate)
736 return err
737 }
738 hs.writeClientHash(certVerify.marshal())
739 }
Nick Harper728eed82016-07-07 17:36:52 -0700740 }
741
742 // Read the client Finished message.
743 msg, err := c.readHandshake()
744 if err != nil {
745 return err
746 }
747 clientFinished, ok := msg.(*finishedMsg)
748 if !ok {
749 c.sendAlert(alertUnexpectedMessage)
750 return unexpectedMessageError(clientFinished, msg)
751 }
752
753 verify := hs.finishedHash.clientSum(handshakeTrafficSecret)
754 if len(verify) != len(clientFinished.verifyData) ||
755 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
756 c.sendAlert(alertHandshakeFailure)
757 return errors.New("tls: client's Finished message was incorrect")
758 }
David Benjamin97a0a082016-07-13 17:57:35 -0400759 hs.writeClientHash(clientFinished.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700760
David Benjamin2aad4062016-07-14 23:15:40 -0400761 // Switch to application data keys on read.
David Benjamin21c00282016-07-18 21:56:23 +0200762 c.in.useTrafficSecret(c.vers, hs.suite, trafficSecret, applicationPhase, clientWrite)
Nick Harper728eed82016-07-07 17:36:52 -0700763
Nick Harper728eed82016-07-07 17:36:52 -0700764 c.cipherSuite = hs.suite
David Benjamin97a0a082016-07-13 17:57:35 -0400765 c.exporterSecret = hs.finishedHash.deriveSecret(masterSecret, exporterLabel)
David Benjamin58104882016-07-18 01:25:41 +0200766 c.resumptionSecret = hs.finishedHash.deriveSecret(masterSecret, resumptionLabel)
767
768 // TODO(davidben): Allow configuring the number of tickets sent for
769 // testing.
770 if !c.config.SessionTicketsDisabled {
771 ticketCount := 2
772 for i := 0; i < ticketCount; i++ {
773 c.SendNewSessionTicket()
774 }
775 }
Nick Harper728eed82016-07-07 17:36:52 -0700776 return nil
777}
778
David Benjaminf25dda92016-07-04 10:05:26 -0700779// processClientHello processes the ClientHello message from the client and
780// decides whether we will perform session resumption.
781func (hs *serverHandshakeState) processClientHello() (isResume bool, err error) {
782 config := hs.c.config
783 c := hs.c
784
785 hs.hello = &serverHelloMsg{
786 isDTLS: c.isDTLS,
787 vers: c.vers,
788 compressionMethod: compressionNone,
789 }
790
Steven Valdez5440fe02016-07-18 12:40:30 -0400791 if config.Bugs.SendServerHelloVersion != 0 {
792 hs.hello.vers = config.Bugs.SendServerHelloVersion
793 }
794
David Benjaminf25dda92016-07-04 10:05:26 -0700795 hs.hello.random = make([]byte, 32)
796 _, err = io.ReadFull(config.rand(), hs.hello.random)
797 if err != nil {
798 c.sendAlert(alertInternalError)
799 return false, err
800 }
David Benjamin1f61f0d2016-07-10 12:20:35 -0400801 // Signal downgrades in the server random, per draft-ietf-tls-tls13-14,
802 // section 6.3.1.2.
Nick Harper85f20c22016-07-04 10:11:59 -0700803 if c.vers <= VersionTLS12 && config.maxVersion(c.isDTLS) >= VersionTLS13 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400804 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS13)
Nick Harper85f20c22016-07-04 10:11:59 -0700805 }
806 if c.vers <= VersionTLS11 && config.maxVersion(c.isDTLS) == VersionTLS12 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400807 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS12)
Nick Harper85f20c22016-07-04 10:11:59 -0700808 }
David Benjaminf25dda92016-07-04 10:05:26 -0700809
810 foundCompression := false
811 // We only support null compression, so check that the client offered it.
812 for _, compression := range hs.clientHello.compressionMethods {
813 if compression == compressionNone {
814 foundCompression = true
815 break
816 }
817 }
818
819 if !foundCompression {
820 c.sendAlert(alertHandshakeFailure)
821 return false, errors.New("tls: client does not support uncompressed connections")
822 }
David Benjamin7d79f832016-07-04 09:20:45 -0700823
824 if err := hs.processClientExtensions(&hs.hello.extensions); err != nil {
825 return false, err
Adam Langley09505632015-07-30 18:10:13 -0700826 }
Adam Langley95c29f32014-06-20 12:00:00 -0700827
828 supportedCurve := false
829 preferredCurves := config.curvePreferences()
830Curves:
831 for _, curve := range hs.clientHello.supportedCurves {
832 for _, supported := range preferredCurves {
833 if supported == curve {
834 supportedCurve = true
835 break Curves
836 }
837 }
838 }
839
840 supportedPointFormat := false
841 for _, pointFormat := range hs.clientHello.supportedPoints {
842 if pointFormat == pointFormatUncompressed {
843 supportedPointFormat = true
844 break
845 }
846 }
847 hs.ellipticOk = supportedCurve && supportedPointFormat
848
Adam Langley95c29f32014-06-20 12:00:00 -0700849 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
850
David Benjamin4b27d9f2015-05-12 22:42:52 -0400851 // For test purposes, check that the peer never offers a session when
852 // renegotiating.
853 if c.cipherSuite != nil && len(hs.clientHello.sessionId) > 0 && c.config.Bugs.FailIfResumeOnRenego {
854 return false, errors.New("tls: offered resumption on renegotiation")
855 }
856
David Benjamindd6fed92015-10-23 17:41:12 -0400857 if c.config.Bugs.FailIfSessionOffered && (len(hs.clientHello.sessionTicket) > 0 || len(hs.clientHello.sessionId) > 0) {
858 return false, errors.New("tls: client offered a session ticket or ID")
859 }
860
Adam Langley95c29f32014-06-20 12:00:00 -0700861 if hs.checkForResumption() {
862 return true, nil
863 }
864
Adam Langley95c29f32014-06-20 12:00:00 -0700865 var preferenceList, supportedList []uint16
866 if c.config.PreferServerCipherSuites {
867 preferenceList = c.config.cipherSuites()
868 supportedList = hs.clientHello.cipherSuites
869 } else {
870 preferenceList = hs.clientHello.cipherSuites
871 supportedList = c.config.cipherSuites()
872 }
873
874 for _, id := range preferenceList {
Nick Harper728eed82016-07-07 17:36:52 -0700875 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk, true); hs.suite != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700876 break
877 }
878 }
879
880 if hs.suite == nil {
881 c.sendAlert(alertHandshakeFailure)
882 return false, errors.New("tls: no cipher suite supported by both client and server")
883 }
884
885 return false, nil
886}
887
David Benjamin7d79f832016-07-04 09:20:45 -0700888// processClientExtensions processes all ClientHello extensions not directly
889// related to cipher suite negotiation and writes responses in serverExtensions.
890func (hs *serverHandshakeState) processClientExtensions(serverExtensions *serverExtensions) error {
891 config := hs.c.config
892 c := hs.c
893
David Benjamin8d315d72016-07-18 01:03:18 +0200894 if c.vers < VersionTLS13 || config.Bugs.NegotiateRenegotiationInfoAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700895 if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) {
896 c.sendAlert(alertHandshakeFailure)
897 return errors.New("tls: renegotiation mismatch")
David Benjamin7d79f832016-07-04 09:20:45 -0700898 }
David Benjamin7d79f832016-07-04 09:20:45 -0700899
Nick Harper728eed82016-07-07 17:36:52 -0700900 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
901 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.clientVerify...)
902 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.serverVerify...)
903 if c.config.Bugs.BadRenegotiationInfo {
904 serverExtensions.secureRenegotiation[0] ^= 0x80
905 }
906 } else {
907 serverExtensions.secureRenegotiation = hs.clientHello.secureRenegotiation
908 }
909
910 if c.noRenegotiationInfo() {
911 serverExtensions.secureRenegotiation = nil
912 }
David Benjamin7d79f832016-07-04 09:20:45 -0700913 }
914
915 serverExtensions.duplicateExtension = c.config.Bugs.DuplicateExtension
916
917 if len(hs.clientHello.serverName) > 0 {
918 c.serverName = hs.clientHello.serverName
919 }
920 if len(config.Certificates) == 0 {
921 c.sendAlert(alertInternalError)
922 return errors.New("tls: no certificates configured")
923 }
924 hs.cert = &config.Certificates[0]
925 if len(hs.clientHello.serverName) > 0 {
926 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
927 }
928 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
929 return errors.New("tls: unexpected server name")
930 }
931
932 if len(hs.clientHello.alpnProtocols) > 0 {
933 if proto := c.config.Bugs.ALPNProtocol; proto != nil {
934 serverExtensions.alpnProtocol = *proto
935 serverExtensions.alpnProtocolEmpty = len(*proto) == 0
936 c.clientProtocol = *proto
937 c.usedALPN = true
938 } else if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
939 serverExtensions.alpnProtocol = selectedProto
940 c.clientProtocol = selectedProto
941 c.usedALPN = true
942 }
943 }
Nick Harper728eed82016-07-07 17:36:52 -0700944
David Benjamin0c40a962016-08-01 12:05:50 -0400945 if len(c.config.Bugs.SendALPN) > 0 {
946 serverExtensions.alpnProtocol = c.config.Bugs.SendALPN
947 }
948
David Benjamin8d315d72016-07-18 01:03:18 +0200949 if c.vers < VersionTLS13 || config.Bugs.NegotiateNPNAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700950 if len(hs.clientHello.alpnProtocols) == 0 || c.config.Bugs.NegotiateALPNAndNPN {
951 // Although sending an empty NPN extension is reasonable, Firefox has
952 // had a bug around this. Best to send nothing at all if
953 // config.NextProtos is empty. See
954 // https://code.google.com/p/go/issues/detail?id=5445.
955 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
956 serverExtensions.nextProtoNeg = true
957 serverExtensions.nextProtos = config.NextProtos
958 serverExtensions.npnLast = config.Bugs.SwapNPNAndALPN
959 }
David Benjamin7d79f832016-07-04 09:20:45 -0700960 }
Steven Valdez143e8b32016-07-11 13:19:03 -0400961 }
David Benjamin7d79f832016-07-04 09:20:45 -0700962
David Benjamin8d315d72016-07-18 01:03:18 +0200963 if c.vers < VersionTLS13 || config.Bugs.NegotiateEMSAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700964 serverExtensions.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !c.config.Bugs.NoExtendedMasterSecret
Steven Valdez143e8b32016-07-11 13:19:03 -0400965 }
David Benjamin7d79f832016-07-04 09:20:45 -0700966
David Benjamin8d315d72016-07-18 01:03:18 +0200967 if c.vers < VersionTLS13 || config.Bugs.NegotiateChannelIDAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700968 if hs.clientHello.channelIDSupported && config.RequestChannelID {
969 serverExtensions.channelIDRequested = true
970 }
David Benjamin7d79f832016-07-04 09:20:45 -0700971 }
972
973 if hs.clientHello.srtpProtectionProfiles != nil {
974 SRTPLoop:
975 for _, p1 := range c.config.SRTPProtectionProfiles {
976 for _, p2 := range hs.clientHello.srtpProtectionProfiles {
977 if p1 == p2 {
978 serverExtensions.srtpProtectionProfile = p1
979 c.srtpProtectionProfile = p1
980 break SRTPLoop
981 }
982 }
983 }
984 }
985
986 if c.config.Bugs.SendSRTPProtectionProfile != 0 {
987 serverExtensions.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
988 }
989
990 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
991 if hs.clientHello.customExtension != *expected {
992 return fmt.Errorf("tls: bad custom extension contents %q", hs.clientHello.customExtension)
993 }
994 }
995 serverExtensions.customExtension = config.Bugs.CustomExtension
996
Steven Valdez143e8b32016-07-11 13:19:03 -0400997 if c.config.Bugs.AdvertiseTicketExtension {
998 serverExtensions.ticketSupported = true
999 }
1000
David Benjamin7d79f832016-07-04 09:20:45 -07001001 return nil
1002}
1003
Adam Langley95c29f32014-06-20 12:00:00 -07001004// checkForResumption returns true if we should perform resumption on this connection.
1005func (hs *serverHandshakeState) checkForResumption() bool {
1006 c := hs.c
1007
David Benjamin405da482016-08-08 17:25:07 -04001008 ticket := hs.clientHello.sessionTicket
1009 if len(ticket) == 0 && len(hs.clientHello.pskIdentities) > 0 && c.config.Bugs.AcceptAnySession {
1010 ticket = hs.clientHello.pskIdentities[0]
1011 }
1012 if len(ticket) > 0 {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001013 if c.config.SessionTicketsDisabled {
1014 return false
1015 }
David Benjaminb0c8db72014-09-24 15:19:56 -04001016
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001017 var ok bool
David Benjamin405da482016-08-08 17:25:07 -04001018 if hs.sessionState, ok = c.decryptTicket(ticket); !ok {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001019 return false
1020 }
1021 } else {
1022 if c.config.ServerSessionCache == nil {
1023 return false
1024 }
1025
1026 var ok bool
1027 sessionId := string(hs.clientHello.sessionId)
1028 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
1029 return false
1030 }
Adam Langley95c29f32014-06-20 12:00:00 -07001031 }
1032
David Benjamin405da482016-08-08 17:25:07 -04001033 if !c.config.Bugs.AcceptAnySession {
1034 // Never resume a session for a different SSL version.
1035 if c.vers != hs.sessionState.vers {
1036 return false
Adam Langley95c29f32014-06-20 12:00:00 -07001037 }
David Benjamin405da482016-08-08 17:25:07 -04001038
1039 cipherSuiteOk := false
1040 // Check that the client is still offering the ciphersuite in the session.
1041 for _, id := range hs.clientHello.cipherSuites {
1042 if id == hs.sessionState.cipherSuite {
1043 cipherSuiteOk = true
1044 break
1045 }
1046 }
1047 if !cipherSuiteOk {
1048 return false
1049 }
Adam Langley95c29f32014-06-20 12:00:00 -07001050 }
1051
1052 // Check that we also support the ciphersuite from the session.
Nick Harper728eed82016-07-07 17:36:52 -07001053 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 -07001054 if hs.suite == nil {
1055 return false
1056 }
1057
1058 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
1059 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
1060 if needClientCerts && !sessionHasClientCerts {
1061 return false
1062 }
1063 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
1064 return false
1065 }
1066
1067 return true
1068}
1069
1070func (hs *serverHandshakeState) doResumeHandshake() error {
1071 c := hs.c
1072
1073 hs.hello.cipherSuite = hs.suite.id
David Benjaminece3de92015-03-16 18:02:20 -04001074 if c.config.Bugs.SendCipherSuite != 0 {
1075 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
1076 }
Adam Langley95c29f32014-06-20 12:00:00 -07001077 // We echo the client's session ID in the ServerHello to let it know
1078 // that we're doing a resumption.
1079 hs.hello.sessionId = hs.clientHello.sessionId
Nick Harperb3d51be2016-07-01 11:43:18 -04001080 hs.hello.extensions.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -07001081
David Benjamin80d1b352016-05-04 19:19:06 -04001082 if c.config.Bugs.SendSCTListOnResume != nil {
Nick Harperb3d51be2016-07-01 11:43:18 -04001083 hs.hello.extensions.sctList = c.config.Bugs.SendSCTListOnResume
David Benjamin80d1b352016-05-04 19:19:06 -04001084 }
1085
Adam Langley95c29f32014-06-20 12:00:00 -07001086 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -04001087 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -04001088 hs.writeClientHash(hs.clientHello.marshal())
1089 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001090
1091 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
1092
1093 if len(hs.sessionState.certificates) > 0 {
1094 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
1095 return err
1096 }
1097 }
1098
1099 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -07001100 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -07001101
1102 return nil
1103}
1104
1105func (hs *serverHandshakeState) doFullHandshake() error {
1106 config := hs.c.config
1107 c := hs.c
1108
David Benjamin48cae082014-10-27 01:06:24 -04001109 isPSK := hs.suite.flags&suitePSK != 0
1110 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001111 hs.hello.extensions.ocspStapling = true
Adam Langley95c29f32014-06-20 12:00:00 -07001112 }
1113
David Benjamin61f95272014-11-25 01:55:35 -05001114 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001115 hs.hello.extensions.sctList = hs.cert.SignedCertificateTimestampList
David Benjamin61f95272014-11-25 01:55:35 -05001116 }
1117
Nick Harperb3d51be2016-07-01 11:43:18 -04001118 hs.hello.extensions.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
Adam Langley95c29f32014-06-20 12:00:00 -07001119 hs.hello.cipherSuite = hs.suite.id
David Benjamin6095de82014-12-27 01:50:38 -05001120 if config.Bugs.SendCipherSuite != 0 {
1121 hs.hello.cipherSuite = config.Bugs.SendCipherSuite
1122 }
Nick Harperb3d51be2016-07-01 11:43:18 -04001123 c.extendedMasterSecret = hs.hello.extensions.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -07001124
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001125 // Generate a session ID if we're to save the session.
Nick Harperb3d51be2016-07-01 11:43:18 -04001126 if !hs.hello.extensions.ticketSupported && config.ServerSessionCache != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001127 hs.hello.sessionId = make([]byte, 32)
1128 if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
1129 c.sendAlert(alertInternalError)
1130 return errors.New("tls: short read from Rand: " + err.Error())
1131 }
1132 }
1133
Adam Langley95c29f32014-06-20 12:00:00 -07001134 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -04001135 hs.writeClientHash(hs.clientHello.marshal())
1136 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001137
1138 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
1139
David Benjamin48cae082014-10-27 01:06:24 -04001140 if !isPSK {
1141 certMsg := new(certificateMsg)
David Benjamin8923c0b2015-06-07 11:42:34 -04001142 if !config.Bugs.EmptyCertificateList {
1143 certMsg.certificates = hs.cert.Certificate
1144 }
David Benjamin48cae082014-10-27 01:06:24 -04001145 if !config.Bugs.UnauthenticatedECDH {
David Benjaminbcb2d912015-02-24 23:45:43 -05001146 certMsgBytes := certMsg.marshal()
David Benjaminbcb2d912015-02-24 23:45:43 -05001147 hs.writeServerHash(certMsgBytes)
1148 c.writeRecord(recordTypeHandshake, certMsgBytes)
David Benjamin48cae082014-10-27 01:06:24 -04001149 }
David Benjamin1c375dd2014-07-12 00:48:23 -04001150 }
Adam Langley95c29f32014-06-20 12:00:00 -07001151
Nick Harperb3d51be2016-07-01 11:43:18 -04001152 if hs.hello.extensions.ocspStapling && !c.config.Bugs.SkipCertificateStatus {
Adam Langley95c29f32014-06-20 12:00:00 -07001153 certStatus := new(certificateStatusMsg)
1154 certStatus.statusType = statusTypeOCSP
1155 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -04001156 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001157 c.writeRecord(recordTypeHandshake, certStatus.marshal())
1158 }
1159
1160 keyAgreement := hs.suite.ka(c.vers)
1161 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
1162 if err != nil {
1163 c.sendAlert(alertHandshakeFailure)
1164 return err
1165 }
Steven Valdez5440fe02016-07-18 12:40:30 -04001166 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
1167 c.curveID = ecdhe.curveID
1168 }
David Benjamin9c651c92014-07-12 13:27:45 -04001169 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -04001170 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001171 c.writeRecord(recordTypeHandshake, skx.marshal())
1172 }
1173
1174 if config.ClientAuth >= RequestClientCert {
1175 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -04001176 certReq := &certificateRequestMsg{
1177 certificateTypes: config.ClientCertificateTypes,
1178 }
1179 if certReq.certificateTypes == nil {
1180 certReq.certificateTypes = []byte{
1181 byte(CertTypeRSASign),
1182 byte(CertTypeECDSASign),
1183 }
Adam Langley95c29f32014-06-20 12:00:00 -07001184 }
1185 if c.vers >= VersionTLS12 {
Nick Harper60edffd2016-06-21 15:19:24 -07001186 certReq.hasSignatureAlgorithm = true
1187 if !config.Bugs.NoSignatureAlgorithms {
David Benjamin7a41d372016-07-09 11:21:54 -07001188 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin000800a2014-11-14 01:43:59 -05001189 }
Adam Langley95c29f32014-06-20 12:00:00 -07001190 }
1191
1192 // An empty list of certificateAuthorities signals to
1193 // the client that it may send any certificate in response
1194 // to our request. When we know the CAs we trust, then
1195 // we can send them down, so that the client can choose
1196 // an appropriate certificate to give to us.
1197 if config.ClientCAs != nil {
1198 certReq.certificateAuthorities = config.ClientCAs.Subjects()
1199 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001200 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001201 c.writeRecord(recordTypeHandshake, certReq.marshal())
1202 }
1203
1204 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001205 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001206 c.writeRecord(recordTypeHandshake, helloDone.marshal())
David Benjamin582ba042016-07-07 12:33:25 -07001207 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001208
1209 var pub crypto.PublicKey // public key for client auth, if any
1210
David Benjamin83f90402015-01-27 01:09:43 -05001211 if err := c.simulatePacketLoss(nil); err != nil {
1212 return err
1213 }
Adam Langley95c29f32014-06-20 12:00:00 -07001214 msg, err := c.readHandshake()
1215 if err != nil {
1216 return err
1217 }
1218
1219 var ok bool
1220 // If we requested a client certificate, then the client must send a
1221 // certificate message, even if it's empty.
1222 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -04001223 var certMsg *certificateMsg
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001224 var certificates [][]byte
1225 if certMsg, ok = msg.(*certificateMsg); ok {
1226 if c.vers == VersionSSL30 && len(certMsg.certificates) == 0 {
1227 return errors.New("tls: empty certificate message in SSL 3.0")
1228 }
1229
1230 hs.writeClientHash(certMsg.marshal())
1231 certificates = certMsg.certificates
1232 } else if c.vers != VersionSSL30 {
1233 // In TLS, the Certificate message is required. In SSL
1234 // 3.0, the peer skips it when sending no certificates.
Adam Langley95c29f32014-06-20 12:00:00 -07001235 c.sendAlert(alertUnexpectedMessage)
1236 return unexpectedMessageError(certMsg, msg)
1237 }
Adam Langley95c29f32014-06-20 12:00:00 -07001238
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001239 if len(certificates) == 0 {
Adam Langley95c29f32014-06-20 12:00:00 -07001240 // The client didn't actually send a certificate
1241 switch config.ClientAuth {
1242 case RequireAnyClientCert, RequireAndVerifyClientCert:
1243 c.sendAlert(alertBadCertificate)
1244 return errors.New("tls: client didn't provide a certificate")
1245 }
1246 }
1247
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001248 pub, err = hs.processCertsFromClient(certificates)
Adam Langley95c29f32014-06-20 12:00:00 -07001249 if err != nil {
1250 return err
1251 }
1252
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001253 if ok {
1254 msg, err = c.readHandshake()
1255 if err != nil {
1256 return err
1257 }
Adam Langley95c29f32014-06-20 12:00:00 -07001258 }
1259 }
1260
1261 // Get client key exchange
1262 ckx, ok := msg.(*clientKeyExchangeMsg)
1263 if !ok {
1264 c.sendAlert(alertUnexpectedMessage)
1265 return unexpectedMessageError(ckx, msg)
1266 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001267 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001268
David Benjamine098ec22014-08-27 23:13:20 -04001269 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
1270 if err != nil {
1271 c.sendAlert(alertHandshakeFailure)
1272 return err
1273 }
Adam Langley75712922014-10-10 16:23:43 -07001274 if c.extendedMasterSecret {
1275 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1276 } else {
1277 if c.config.Bugs.RequireExtendedMasterSecret {
1278 return errors.New("tls: extended master secret required but not supported by peer")
1279 }
1280 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
1281 }
David Benjamine098ec22014-08-27 23:13:20 -04001282
Adam Langley95c29f32014-06-20 12:00:00 -07001283 // If we received a client cert in response to our certificate request message,
1284 // the client will send us a certificateVerifyMsg immediately after the
1285 // clientKeyExchangeMsg. This message is a digest of all preceding
1286 // handshake-layer messages that is signed using the private key corresponding
1287 // to the client's certificate. This allows us to verify that the client is in
1288 // possession of the private key of the certificate.
1289 if len(c.peerCertificates) > 0 {
1290 msg, err = c.readHandshake()
1291 if err != nil {
1292 return err
1293 }
1294 certVerify, ok := msg.(*certificateVerifyMsg)
1295 if !ok {
1296 c.sendAlert(alertUnexpectedMessage)
1297 return unexpectedMessageError(certVerify, msg)
1298 }
1299
David Benjaminde620d92014-07-18 15:03:41 -04001300 // Determine the signature type.
Nick Harper60edffd2016-06-21 15:19:24 -07001301 var sigAlg signatureAlgorithm
1302 if certVerify.hasSignatureAlgorithm {
1303 sigAlg = certVerify.signatureAlgorithm
Nick Harper60edffd2016-06-21 15:19:24 -07001304 c.peerSignatureAlgorithm = sigAlg
David Benjaminde620d92014-07-18 15:03:41 -04001305 }
1306
Nick Harper60edffd2016-06-21 15:19:24 -07001307 if c.vers > VersionSSL30 {
David Benjamin1fb125c2016-07-08 18:52:12 -07001308 err = verifyMessage(c.vers, pub, c.config, sigAlg, hs.finishedHash.buffer, certVerify.signature)
Nick Harper60edffd2016-06-21 15:19:24 -07001309 } else {
1310 // SSL 3.0's client certificate construction is
1311 // incompatible with signatureAlgorithm.
1312 rsaPub, ok := pub.(*rsa.PublicKey)
1313 if !ok {
1314 err = errors.New("unsupported key type for client certificate")
1315 } else {
1316 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
1317 err = rsa.VerifyPKCS1v15(rsaPub, crypto.MD5SHA1, digest, certVerify.signature)
David Benjaminde620d92014-07-18 15:03:41 -04001318 }
Adam Langley95c29f32014-06-20 12:00:00 -07001319 }
1320 if err != nil {
1321 c.sendAlert(alertBadCertificate)
1322 return errors.New("could not validate signature of connection nonces: " + err.Error())
1323 }
1324
David Benjamin83c0bc92014-08-04 01:23:53 -04001325 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001326 }
1327
David Benjamine098ec22014-08-27 23:13:20 -04001328 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001329
1330 return nil
1331}
1332
1333func (hs *serverHandshakeState) establishKeys() error {
1334 c := hs.c
1335
1336 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001337 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 -07001338
1339 var clientCipher, serverCipher interface{}
1340 var clientHash, serverHash macFunction
1341
1342 if hs.suite.aead == nil {
1343 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
1344 clientHash = hs.suite.mac(c.vers, clientMAC)
1345 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
1346 serverHash = hs.suite.mac(c.vers, serverMAC)
1347 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001348 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1349 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001350 }
1351
1352 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
1353 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
1354
1355 return nil
1356}
1357
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001358func (hs *serverHandshakeState) readFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001359 c := hs.c
1360
1361 c.readRecord(recordTypeChangeCipherSpec)
1362 if err := c.in.error(); err != nil {
1363 return err
1364 }
1365
Nick Harperb3d51be2016-07-01 11:43:18 -04001366 if hs.hello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001367 msg, err := c.readHandshake()
1368 if err != nil {
1369 return err
1370 }
1371 nextProto, ok := msg.(*nextProtoMsg)
1372 if !ok {
1373 c.sendAlert(alertUnexpectedMessage)
1374 return unexpectedMessageError(nextProto, msg)
1375 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001376 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001377 c.clientProtocol = nextProto.proto
1378 }
1379
Nick Harperb3d51be2016-07-01 11:43:18 -04001380 if hs.hello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001381 msg, err := c.readHandshake()
1382 if err != nil {
1383 return err
1384 }
David Benjamin24599a82016-06-30 18:56:53 -04001385 channelIDMsg, ok := msg.(*channelIDMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001386 if !ok {
1387 c.sendAlert(alertUnexpectedMessage)
David Benjamin24599a82016-06-30 18:56:53 -04001388 return unexpectedMessageError(channelIDMsg, msg)
David Benjamind30a9902014-08-24 01:44:23 -04001389 }
David Benjamin24599a82016-06-30 18:56:53 -04001390 x := new(big.Int).SetBytes(channelIDMsg.channelID[0:32])
1391 y := new(big.Int).SetBytes(channelIDMsg.channelID[32:64])
1392 r := new(big.Int).SetBytes(channelIDMsg.channelID[64:96])
1393 s := new(big.Int).SetBytes(channelIDMsg.channelID[96:128])
David Benjamind30a9902014-08-24 01:44:23 -04001394 if !elliptic.P256().IsOnCurve(x, y) {
1395 return errors.New("tls: invalid channel ID public key")
1396 }
1397 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
1398 var resumeHash []byte
1399 if isResume {
1400 resumeHash = hs.sessionState.handshakeHash
1401 }
1402 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
1403 return errors.New("tls: invalid channel ID signature")
1404 }
1405 c.channelID = channelID
1406
David Benjamin24599a82016-06-30 18:56:53 -04001407 hs.writeClientHash(channelIDMsg.marshal())
David Benjamind30a9902014-08-24 01:44:23 -04001408 }
1409
Adam Langley95c29f32014-06-20 12:00:00 -07001410 msg, err := c.readHandshake()
1411 if err != nil {
1412 return err
1413 }
1414 clientFinished, ok := msg.(*finishedMsg)
1415 if !ok {
1416 c.sendAlert(alertUnexpectedMessage)
1417 return unexpectedMessageError(clientFinished, msg)
1418 }
1419
1420 verify := hs.finishedHash.clientSum(hs.masterSecret)
1421 if len(verify) != len(clientFinished.verifyData) ||
1422 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
1423 c.sendAlert(alertHandshakeFailure)
1424 return errors.New("tls: client's Finished message is incorrect")
1425 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001426 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001427 copy(out, clientFinished.verifyData)
Adam Langley95c29f32014-06-20 12:00:00 -07001428
David Benjamin83c0bc92014-08-04 01:23:53 -04001429 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001430 return nil
1431}
1432
1433func (hs *serverHandshakeState) sendSessionTicket() error {
Adam Langley95c29f32014-06-20 12:00:00 -07001434 c := hs.c
Adam Langley95c29f32014-06-20 12:00:00 -07001435 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -04001436 vers: c.vers,
1437 cipherSuite: hs.suite.id,
1438 masterSecret: hs.masterSecret,
1439 certificates: hs.certsFromClient,
1440 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -07001441 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001442
Nick Harperb3d51be2016-07-01 11:43:18 -04001443 if !hs.hello.extensions.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001444 if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
1445 c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
1446 }
1447 return nil
1448 }
1449
1450 m := new(newSessionTicketMsg)
1451
David Benjamindd6fed92015-10-23 17:41:12 -04001452 if !c.config.Bugs.SendEmptySessionTicket {
1453 var err error
1454 m.ticket, err = c.encryptTicket(&state)
1455 if err != nil {
1456 return err
1457 }
Adam Langley95c29f32014-06-20 12:00:00 -07001458 }
Adam Langley95c29f32014-06-20 12:00:00 -07001459
David Benjamin83c0bc92014-08-04 01:23:53 -04001460 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001461 c.writeRecord(recordTypeHandshake, m.marshal())
1462
1463 return nil
1464}
1465
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001466func (hs *serverHandshakeState) sendFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001467 c := hs.c
1468
David Benjamin86271ee2014-07-21 16:14:03 -04001469 finished := new(finishedMsg)
1470 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001471 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001472 if c.config.Bugs.BadFinished {
1473 finished.verifyData[0]++
1474 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001475 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001476 hs.finishedBytes = finished.marshal()
1477 hs.writeServerHash(hs.finishedBytes)
1478 postCCSBytes := hs.finishedBytes
David Benjamin86271ee2014-07-21 16:14:03 -04001479
1480 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
1481 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
1482 postCCSBytes = postCCSBytes[5:]
David Benjamin61672812016-07-14 23:10:43 -04001483 } else if c.config.Bugs.SendUnencryptedFinished {
1484 c.writeRecord(recordTypeHandshake, postCCSBytes)
1485 postCCSBytes = nil
David Benjamin86271ee2014-07-21 16:14:03 -04001486 }
David Benjamin582ba042016-07-07 12:33:25 -07001487 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001488
David Benjamina0e52232014-07-19 17:39:58 -04001489 if !c.config.Bugs.SkipChangeCipherSpec {
David Benjamin8411b242015-11-26 12:07:28 -05001490 ccs := []byte{1}
1491 if c.config.Bugs.BadChangeCipherSpec != nil {
1492 ccs = c.config.Bugs.BadChangeCipherSpec
1493 }
1494 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamina0e52232014-07-19 17:39:58 -04001495 }
Adam Langley95c29f32014-06-20 12:00:00 -07001496
David Benjamin4189bd92015-01-25 23:52:39 -05001497 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1498 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1499 }
David Benjamindc3da932015-03-12 15:09:02 -04001500 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1501 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1502 return errors.New("tls: simulating post-CCS alert")
1503 }
David Benjamin4189bd92015-01-25 23:52:39 -05001504
David Benjamin61672812016-07-14 23:10:43 -04001505 if !c.config.Bugs.SkipFinished && len(postCCSBytes) > 0 {
David Benjaminb80168e2015-02-08 18:30:14 -05001506 c.writeRecord(recordTypeHandshake, postCCSBytes)
David Benjamin02edcd02016-07-27 17:40:37 -04001507 if c.config.Bugs.SendExtraFinished {
1508 c.writeRecord(recordTypeHandshake, finished.marshal())
1509 }
1510
David Benjamin12d2c482016-07-24 10:56:51 -04001511 if !c.config.Bugs.PackHelloRequestWithFinished {
1512 // Defer flushing until renegotiation.
1513 c.flushHandshake()
1514 }
David Benjaminb3774b92015-01-31 17:16:01 -05001515 }
Adam Langley95c29f32014-06-20 12:00:00 -07001516
David Benjaminc565ebb2015-04-03 04:06:36 -04001517 c.cipherSuite = hs.suite
Adam Langley95c29f32014-06-20 12:00:00 -07001518
1519 return nil
1520}
1521
1522// processCertsFromClient takes a chain of client certificates either from a
1523// Certificates message or from a sessionState and verifies them. It returns
1524// the public key of the leaf certificate.
1525func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
1526 c := hs.c
1527
1528 hs.certsFromClient = certificates
1529 certs := make([]*x509.Certificate, len(certificates))
1530 var err error
1531 for i, asn1Data := range certificates {
1532 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
1533 c.sendAlert(alertBadCertificate)
1534 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
1535 }
1536 }
1537
1538 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
1539 opts := x509.VerifyOptions{
1540 Roots: c.config.ClientCAs,
1541 CurrentTime: c.config.time(),
1542 Intermediates: x509.NewCertPool(),
1543 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
1544 }
1545
1546 for _, cert := range certs[1:] {
1547 opts.Intermediates.AddCert(cert)
1548 }
1549
1550 chains, err := certs[0].Verify(opts)
1551 if err != nil {
1552 c.sendAlert(alertBadCertificate)
1553 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
1554 }
1555
1556 ok := false
1557 for _, ku := range certs[0].ExtKeyUsage {
1558 if ku == x509.ExtKeyUsageClientAuth {
1559 ok = true
1560 break
1561 }
1562 }
1563 if !ok {
1564 c.sendAlert(alertHandshakeFailure)
1565 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
1566 }
1567
1568 c.verifiedChains = chains
1569 }
1570
1571 if len(certs) > 0 {
1572 var pub crypto.PublicKey
1573 switch key := certs[0].PublicKey.(type) {
1574 case *ecdsa.PublicKey, *rsa.PublicKey:
1575 pub = key
1576 default:
1577 c.sendAlert(alertUnsupportedCertificate)
1578 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
1579 }
1580 c.peerCertificates = certs
1581 return pub, nil
1582 }
1583
1584 return nil, nil
1585}
1586
David Benjamin83c0bc92014-08-04 01:23:53 -04001587func (hs *serverHandshakeState) writeServerHash(msg []byte) {
1588 // writeServerHash is called before writeRecord.
1589 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1590}
1591
1592func (hs *serverHandshakeState) writeClientHash(msg []byte) {
1593 // writeClientHash is called after readHandshake.
1594 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1595}
1596
1597func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
1598 if hs.c.isDTLS {
1599 // This is somewhat hacky. DTLS hashes a slightly different format.
1600 // First, the TLS header.
1601 hs.finishedHash.Write(msg[:4])
1602 // Then the sequence number and reassembled fragment offset (always 0).
1603 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1604 // Then the reassembled fragment (always equal to the message length).
1605 hs.finishedHash.Write(msg[1:4])
1606 // And then the message body.
1607 hs.finishedHash.Write(msg[4:])
1608 } else {
1609 hs.finishedHash.Write(msg)
1610 }
1611}
1612
Adam Langley95c29f32014-06-20 12:00:00 -07001613// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
1614// is acceptable to use.
Nick Harper728eed82016-07-07 17:36:52 -07001615func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk, pskOk bool) *cipherSuite {
Adam Langley95c29f32014-06-20 12:00:00 -07001616 for _, supported := range supportedCipherSuites {
1617 if id == supported {
1618 var candidate *cipherSuite
1619
1620 for _, s := range cipherSuites {
1621 if s.id == id {
1622 candidate = s
1623 break
1624 }
1625 }
1626 if candidate == nil {
1627 continue
1628 }
1629 // Don't select a ciphersuite which we can't
1630 // support for this client.
David Benjamin0407e762016-06-17 16:41:18 -04001631 if !c.config.Bugs.EnableAllCiphers {
Nick Harper728eed82016-07-07 17:36:52 -07001632 if (candidate.flags&suitePSK != 0) && !pskOk {
1633 continue
1634 }
David Benjamin0407e762016-06-17 16:41:18 -04001635 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
1636 continue
1637 }
1638 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
1639 continue
1640 }
1641 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
1642 continue
1643 }
Nick Harper728eed82016-07-07 17:36:52 -07001644 if version >= VersionTLS13 && candidate.flags&suiteTLS13 == 0 {
1645 continue
1646 }
David Benjamin0407e762016-06-17 16:41:18 -04001647 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
1648 continue
1649 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001650 }
Adam Langley95c29f32014-06-20 12:00:00 -07001651 return candidate
1652 }
1653 }
1654
1655 return nil
1656}
David Benjaminf93995b2015-11-05 18:23:20 -05001657
1658func isTLS12Cipher(id uint16) bool {
1659 for _, cipher := range cipherSuites {
1660 if cipher.id != id {
1661 continue
1662 }
1663 return cipher.flags&suiteTLS12 != 0
1664 }
1665 // Unknown cipher.
1666 return false
1667}