blob: 85d4ca858aac94e15476549aa76246ed8e08321a [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
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400208 var clientVersion uint16
209 if c.isDTLS {
210 if hs.clientHello.vers <= 0xfefd {
211 clientVersion = VersionTLS12
212 } else if hs.clientHello.vers <= 0xfeff {
213 clientVersion = VersionTLS10
214 }
215 } else {
216 if hs.clientHello.vers >= VersionTLS13 {
217 clientVersion = VersionTLS13
218 } else if hs.clientHello.vers >= VersionTLS12 {
219 clientVersion = VersionTLS12
220 } else if hs.clientHello.vers >= VersionTLS11 {
221 clientVersion = VersionTLS11
222 } else if hs.clientHello.vers >= VersionTLS10 {
223 clientVersion = VersionTLS10
224 } else if hs.clientHello.vers >= VersionSSL30 {
225 clientVersion = VersionSSL30
226 }
227 }
228
229 if config.Bugs.NegotiateVersion != 0 {
230 c.vers = config.Bugs.NegotiateVersion
231 } else if c.haveVers && config.Bugs.NegotiateVersionOnRenego != 0 {
232 c.vers = config.Bugs.NegotiateVersionOnRenego
233 } else {
234 c.vers, ok = config.mutualVersion(clientVersion, c.isDTLS)
235 if !ok {
236 c.sendAlert(alertProtocolVersion)
237 return fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
238 }
239 }
240 c.haveVers = true
David Benjaminc44b1df2014-11-23 12:11:01 -0500241
David Benjamin6ae7f072015-01-26 10:22:13 -0500242 // Reject < 1.2 ClientHellos with signature_algorithms.
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400243 if clientVersion < VersionTLS12 && len(hs.clientHello.signatureAlgorithms) > 0 {
David Benjaminf25dda92016-07-04 10:05:26 -0700244 return fmt.Errorf("tls: client included signature_algorithms before TLS 1.2")
David Benjamin72dc7832015-03-16 17:49:43 -0400245 }
David Benjamin6ae7f072015-01-26 10:22:13 -0500246
David Benjaminf93995b2015-11-05 18:23:20 -0500247 // Check the client cipher list is consistent with the version.
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400248 if clientVersion < VersionTLS12 {
David Benjaminf93995b2015-11-05 18:23:20 -0500249 for _, id := range hs.clientHello.cipherSuites {
250 if isTLS12Cipher(id) {
David Benjaminf25dda92016-07-04 10:05:26 -0700251 return fmt.Errorf("tls: client offered TLS 1.2 cipher before TLS 1.2")
David Benjaminf93995b2015-11-05 18:23:20 -0500252 }
253 }
254 }
255
David Benjamin405da482016-08-08 17:25:07 -0400256 if config.Bugs.ExpectNoTLS12Session {
257 if len(hs.clientHello.sessionId) > 0 {
258 return fmt.Errorf("tls: client offered an unexpected session ID")
259 }
260 if len(hs.clientHello.sessionTicket) > 0 {
261 return fmt.Errorf("tls: client offered an unexpected session ticket")
262 }
263 }
264
265 if config.Bugs.ExpectNoTLS13PSK && len(hs.clientHello.pskIdentities) > 0 {
266 return fmt.Errorf("tls: client offered unexpected PSK identities")
267 }
268
David Benjamin65ac9972016-09-02 21:35:25 -0400269 var scsvFound, greaseFound bool
David Benjaminf25dda92016-07-04 10:05:26 -0700270 for _, cipherSuite := range hs.clientHello.cipherSuites {
271 if cipherSuite == fallbackSCSV {
272 scsvFound = true
David Benjamin65ac9972016-09-02 21:35:25 -0400273 }
274 if isGREASEValue(cipherSuite) {
275 greaseFound = true
David Benjaminf25dda92016-07-04 10:05:26 -0700276 }
277 }
278
279 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
280 return errors.New("tls: no fallback SCSV found when expected")
281 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
282 return errors.New("tls: fallback SCSV found when not expected")
283 }
284
David Benjamin65ac9972016-09-02 21:35:25 -0400285 if !greaseFound && config.Bugs.ExpectGREASE {
286 return errors.New("tls: no GREASE cipher suite value found")
287 }
288
289 greaseFound = false
290 for _, curve := range hs.clientHello.supportedCurves {
291 if isGREASEValue(uint16(curve)) {
292 greaseFound = true
293 break
294 }
295 }
296
297 if !greaseFound && config.Bugs.ExpectGREASE {
298 return errors.New("tls: no GREASE curve value found")
299 }
300
301 if len(hs.clientHello.keyShares) > 0 {
302 greaseFound = false
303 for _, keyShare := range hs.clientHello.keyShares {
304 if isGREASEValue(uint16(keyShare.group)) {
305 greaseFound = true
306 break
307 }
308 }
309
310 if !greaseFound && config.Bugs.ExpectGREASE {
311 return errors.New("tls: no GREASE curve value found")
312 }
313 }
314
David Benjaminf25dda92016-07-04 10:05:26 -0700315 if config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
David Benjamin7a41d372016-07-09 11:21:54 -0700316 hs.clientHello.signatureAlgorithms = config.signSignatureAlgorithms()
David Benjaminf25dda92016-07-04 10:05:26 -0700317 }
318 if config.Bugs.IgnorePeerCurvePreferences {
319 hs.clientHello.supportedCurves = config.curvePreferences()
320 }
321 if config.Bugs.IgnorePeerCipherPreferences {
322 hs.clientHello.cipherSuites = config.cipherSuites()
323 }
324
325 return nil
326}
327
Nick Harper728eed82016-07-07 17:36:52 -0700328func (hs *serverHandshakeState) doTLS13Handshake() error {
329 c := hs.c
330 config := c.config
331
332 hs.hello = &serverHelloMsg{
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400333 isDTLS: c.isDTLS,
334 vers: versionToWire(c.vers, c.isDTLS),
335 versOverride: config.Bugs.SendServerHelloVersion,
Steven Valdez5440fe02016-07-18 12:40:30 -0400336 }
337
Nick Harper728eed82016-07-07 17:36:52 -0700338 hs.hello.random = make([]byte, 32)
339 if _, err := io.ReadFull(config.rand(), hs.hello.random); err != nil {
340 c.sendAlert(alertInternalError)
341 return err
342 }
343
344 // TLS 1.3 forbids clients from advertising any non-null compression.
345 if len(hs.clientHello.compressionMethods) != 1 || hs.clientHello.compressionMethods[0] != compressionNone {
346 return errors.New("tls: client sent compression method other than null for TLS 1.3")
347 }
348
349 // Prepare an EncryptedExtensions message, but do not send it yet.
350 encryptedExtensions := new(encryptedExtensionsMsg)
Steven Valdez143e8b32016-07-11 13:19:03 -0400351 encryptedExtensions.empty = config.Bugs.EmptyEncryptedExtensions
Nick Harper728eed82016-07-07 17:36:52 -0700352 if err := hs.processClientExtensions(&encryptedExtensions.extensions); err != nil {
353 return err
354 }
355
356 supportedCurve := false
357 var selectedCurve CurveID
358 preferredCurves := config.curvePreferences()
359Curves:
360 for _, curve := range hs.clientHello.supportedCurves {
361 for _, supported := range preferredCurves {
362 if supported == curve {
363 supportedCurve = true
364 selectedCurve = curve
365 break Curves
366 }
367 }
368 }
369
370 _, ecdsaOk := hs.cert.PrivateKey.(*ecdsa.PrivateKey)
371
David Benjamin405da482016-08-08 17:25:07 -0400372 pskIdentities := hs.clientHello.pskIdentities
373 if len(pskIdentities) == 0 && len(hs.clientHello.sessionTicket) > 0 && c.config.Bugs.AcceptAnySession {
374 pskIdentities = [][]uint8{hs.clientHello.sessionTicket}
375 }
376 for i, pskIdentity := range pskIdentities {
Nick Harper0b3625b2016-07-25 16:16:28 -0700377 sessionState, ok := c.decryptTicket(pskIdentity)
378 if !ok {
379 continue
380 }
David Benjamin405da482016-08-08 17:25:07 -0400381 if !config.Bugs.AcceptAnySession {
382 if sessionState.vers != c.vers && c.config.Bugs.AcceptAnySession {
383 continue
384 }
385 if sessionState.ticketFlags&ticketAllowDHEResumption == 0 {
386 continue
387 }
388 if sessionState.ticketExpiration.Before(c.config.time()) {
389 continue
390 }
Nick Harper0b3625b2016-07-25 16:16:28 -0700391 }
David Benjamin405da482016-08-08 17:25:07 -0400392
Nick Harper0b3625b2016-07-25 16:16:28 -0700393 suiteId := ecdhePSKSuite(sessionState.cipherSuite)
David Benjamin405da482016-08-08 17:25:07 -0400394
395 // Check the client offered the cipher.
396 clientCipherSuites := hs.clientHello.cipherSuites
397 if config.Bugs.AcceptAnySession {
398 clientCipherSuites = []uint16{suiteId}
399 }
400 suite := mutualCipherSuite(clientCipherSuites, suiteId)
401
David Benjamin46662482016-08-17 00:51:00 -0400402 // Check the cipher is enabled by the server or is a resumption
403 // suite of one enabled by the server. Account for the cipher
404 // change on resume.
405 //
406 // TODO(davidben): The ecdhePSKSuite mess will be gone with the
407 // new cipher negotiation scheme.
Nick Harper0b3625b2016-07-25 16:16:28 -0700408 var found bool
409 for _, id := range config.cipherSuites() {
David Benjamin46662482016-08-17 00:51:00 -0400410 if ecdhePSKSuite(id) == suiteId {
Nick Harper0b3625b2016-07-25 16:16:28 -0700411 found = true
412 break
413 }
414 }
David Benjamin405da482016-08-08 17:25:07 -0400415
Nick Harper0b3625b2016-07-25 16:16:28 -0700416 if suite != nil && found {
417 hs.sessionState = sessionState
418 hs.suite = suite
419 hs.hello.hasPSKIdentity = true
420 hs.hello.pskIdentity = uint16(i)
421 c.didResume = true
422 break
423 }
Nick Harper728eed82016-07-07 17:36:52 -0700424 }
425
Nick Harper0b3625b2016-07-25 16:16:28 -0700426 // If not resuming, select the cipher suite.
427 if hs.suite == nil {
428 var preferenceList, supportedList []uint16
429 if config.PreferServerCipherSuites {
430 preferenceList = config.cipherSuites()
431 supportedList = hs.clientHello.cipherSuites
432 } else {
433 preferenceList = hs.clientHello.cipherSuites
434 supportedList = config.cipherSuites()
435 }
436
437 for _, id := range preferenceList {
438 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, supportedCurve, ecdsaOk, false); hs.suite != nil {
439 break
440 }
Nick Harper728eed82016-07-07 17:36:52 -0700441 }
442 }
443
444 if hs.suite == nil {
445 c.sendAlert(alertHandshakeFailure)
446 return errors.New("tls: no cipher suite supported by both client and server")
447 }
448
449 hs.hello.cipherSuite = hs.suite.id
Steven Valdez0ee2e112016-07-15 06:51:15 -0400450 if c.config.Bugs.SendCipherSuite != 0 {
451 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
452 }
453
Nick Harper728eed82016-07-07 17:36:52 -0700454 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
455 hs.finishedHash.discardHandshakeBuffer()
456 hs.writeClientHash(hs.clientHello.marshal())
457
458 // Resolve PSK and compute the early secret.
Nick Harper0b3625b2016-07-25 16:16:28 -0700459 var psk []byte
460 // The only way for hs.suite to be a PSK suite yet for there to be
461 // no sessionState is if config.Bugs.EnableAllCiphers is true and
462 // the test runner forced us to negotiated a PSK suite. It doesn't
463 // really matter what we do here so long as we continue the
464 // handshake and let the client error out.
465 if hs.suite.flags&suitePSK != 0 && hs.sessionState != nil {
466 psk = deriveResumptionPSK(hs.suite, hs.sessionState.masterSecret)
467 hs.finishedHash.setResumptionContext(deriveResumptionContext(hs.suite, hs.sessionState.masterSecret))
468 } else {
469 psk = hs.finishedHash.zeroSecret()
470 hs.finishedHash.setResumptionContext(hs.finishedHash.zeroSecret())
471 }
Nick Harper728eed82016-07-07 17:36:52 -0700472
473 earlySecret := hs.finishedHash.extractKey(hs.finishedHash.zeroSecret(), psk)
474
475 // Resolve ECDHE and compute the handshake secret.
476 var ecdheSecret []byte
Steven Valdez143e8b32016-07-11 13:19:03 -0400477 if hs.suite.flags&suiteECDHE != 0 && !config.Bugs.MissingKeyShare {
Nick Harper728eed82016-07-07 17:36:52 -0700478 // Look for the key share corresponding to our selected curve.
479 var selectedKeyShare *keyShareEntry
480 for i := range hs.clientHello.keyShares {
481 if hs.clientHello.keyShares[i].group == selectedCurve {
482 selectedKeyShare = &hs.clientHello.keyShares[i]
483 break
484 }
485 }
486
David Benjamine73c7f42016-08-17 00:29:33 -0400487 if config.Bugs.ExpectMissingKeyShare && selectedKeyShare != nil {
488 return errors.New("tls: expected missing key share")
489 }
490
Steven Valdez5440fe02016-07-18 12:40:30 -0400491 sendHelloRetryRequest := selectedKeyShare == nil
492 if config.Bugs.UnnecessaryHelloRetryRequest {
493 sendHelloRetryRequest = true
494 }
495 if config.Bugs.SkipHelloRetryRequest {
496 sendHelloRetryRequest = false
497 }
498 if sendHelloRetryRequest {
499 firstTime := true
500 ResendHelloRetryRequest:
Nick Harperdcfbc672016-07-16 17:47:31 +0200501 // Send HelloRetryRequest.
502 helloRetryRequestMsg := helloRetryRequestMsg{
503 vers: c.vers,
504 cipherSuite: hs.hello.cipherSuite,
505 selectedGroup: selectedCurve,
506 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400507 if config.Bugs.SendHelloRetryRequestCurve != 0 {
508 helloRetryRequestMsg.selectedGroup = config.Bugs.SendHelloRetryRequestCurve
509 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200510 hs.writeServerHash(helloRetryRequestMsg.marshal())
511 c.writeRecord(recordTypeHandshake, helloRetryRequestMsg.marshal())
David Benjamine73c7f42016-08-17 00:29:33 -0400512 c.flushHandshake()
Nick Harperdcfbc672016-07-16 17:47:31 +0200513
514 // Read new ClientHello.
515 newMsg, err := c.readHandshake()
516 if err != nil {
517 return err
518 }
519 newClientHello, ok := newMsg.(*clientHelloMsg)
520 if !ok {
521 c.sendAlert(alertUnexpectedMessage)
522 return unexpectedMessageError(newClientHello, newMsg)
523 }
524 hs.writeClientHash(newClientHello.marshal())
525
526 // Check that the new ClientHello matches the old ClientHello, except for
527 // the addition of the new KeyShareEntry at the end of the list, and
528 // removing the EarlyDataIndication extension (if present).
529 newKeyShares := newClientHello.keyShares
530 if len(newKeyShares) == 0 || newKeyShares[len(newKeyShares)-1].group != selectedCurve {
531 return errors.New("tls: KeyShare from HelloRetryRequest not present in new ClientHello")
532 }
533 oldClientHelloCopy := *hs.clientHello
534 oldClientHelloCopy.raw = nil
535 oldClientHelloCopy.hasEarlyData = false
536 oldClientHelloCopy.earlyDataContext = nil
537 newClientHelloCopy := *newClientHello
538 newClientHelloCopy.raw = nil
539 newClientHelloCopy.keyShares = newKeyShares[:len(newKeyShares)-1]
540 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
541 return errors.New("tls: new ClientHello does not match")
542 }
543
Steven Valdez5440fe02016-07-18 12:40:30 -0400544 if firstTime && config.Bugs.SecondHelloRetryRequest {
545 firstTime = false
546 goto ResendHelloRetryRequest
547 }
548
Nick Harperdcfbc672016-07-16 17:47:31 +0200549 selectedKeyShare = &newKeyShares[len(newKeyShares)-1]
Nick Harper728eed82016-07-07 17:36:52 -0700550 }
551
552 // Once a curve has been selected and a key share identified,
553 // the server needs to generate a public value and send it in
554 // the ServerHello.
Steven Valdez5440fe02016-07-18 12:40:30 -0400555 curve, ok := curveForCurveID(selectedCurve)
Nick Harper728eed82016-07-07 17:36:52 -0700556 if !ok {
557 panic("tls: server failed to look up curve ID")
558 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400559 c.curveID = selectedCurve
560
561 var peerKey []byte
562 if config.Bugs.SkipHelloRetryRequest {
563 // If skipping HelloRetryRequest, use a random key to
564 // avoid crashing.
565 curve2, _ := curveForCurveID(selectedCurve)
566 var err error
567 peerKey, err = curve2.offer(config.rand())
568 if err != nil {
569 return err
570 }
571 } else {
572 peerKey = selectedKeyShare.keyExchange
573 }
574
Nick Harper728eed82016-07-07 17:36:52 -0700575 var publicKey []byte
576 var err error
Steven Valdez5440fe02016-07-18 12:40:30 -0400577 publicKey, ecdheSecret, err = curve.accept(config.rand(), peerKey)
Nick Harper728eed82016-07-07 17:36:52 -0700578 if err != nil {
579 c.sendAlert(alertHandshakeFailure)
580 return err
581 }
582 hs.hello.hasKeyShare = true
Steven Valdez0ee2e112016-07-15 06:51:15 -0400583
Steven Valdez5440fe02016-07-18 12:40:30 -0400584 curveID := selectedCurve
Steven Valdez0ee2e112016-07-15 06:51:15 -0400585 if c.config.Bugs.SendCurve != 0 {
586 curveID = config.Bugs.SendCurve
587 }
588 if c.config.Bugs.InvalidECDHPoint {
589 publicKey[0] ^= 0xff
590 }
591
Nick Harper728eed82016-07-07 17:36:52 -0700592 hs.hello.keyShare = keyShareEntry{
Steven Valdez0ee2e112016-07-15 06:51:15 -0400593 group: curveID,
Nick Harper728eed82016-07-07 17:36:52 -0700594 keyExchange: publicKey,
595 }
Steven Valdez143e8b32016-07-11 13:19:03 -0400596
597 if config.Bugs.EncryptedExtensionsWithKeyShare {
598 encryptedExtensions.extensions.hasKeyShare = true
599 encryptedExtensions.extensions.keyShare = keyShareEntry{
600 group: curveID,
601 keyExchange: publicKey,
602 }
603 }
Nick Harper728eed82016-07-07 17:36:52 -0700604 } else {
605 ecdheSecret = hs.finishedHash.zeroSecret()
606 }
607
608 // Send unencrypted ServerHello.
609 hs.writeServerHash(hs.hello.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400610 if config.Bugs.PartialEncryptedExtensionsWithServerHello {
611 helloBytes := hs.hello.marshal()
612 toWrite := make([]byte, 0, len(helloBytes)+1)
613 toWrite = append(toWrite, helloBytes...)
614 toWrite = append(toWrite, typeEncryptedExtensions)
615 c.writeRecord(recordTypeHandshake, toWrite)
616 } else {
617 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
618 }
Nick Harper728eed82016-07-07 17:36:52 -0700619 c.flushHandshake()
620
621 // Compute the handshake secret.
622 handshakeSecret := hs.finishedHash.extractKey(earlySecret, ecdheSecret)
623
624 // Switch to handshake traffic keys.
625 handshakeTrafficSecret := hs.finishedHash.deriveSecret(handshakeSecret, handshakeTrafficLabel)
David Benjamin21c00282016-07-18 21:56:23 +0200626 c.out.useTrafficSecret(c.vers, hs.suite, handshakeTrafficSecret, handshakePhase, serverWrite)
627 c.in.useTrafficSecret(c.vers, hs.suite, handshakeTrafficSecret, handshakePhase, clientWrite)
Nick Harper728eed82016-07-07 17:36:52 -0700628
Nick Harper0b3625b2016-07-25 16:16:28 -0700629 if hs.suite.flags&suitePSK == 0 {
David Benjamin615119a2016-07-06 19:22:55 -0700630 if hs.clientHello.ocspStapling {
631 encryptedExtensions.extensions.ocspResponse = hs.cert.OCSPStaple
632 }
633 if hs.clientHello.sctListSupported {
634 encryptedExtensions.extensions.sctList = hs.cert.SignedCertificateTimestampList
635 }
636 }
637
Nick Harper728eed82016-07-07 17:36:52 -0700638 // Send EncryptedExtensions.
639 hs.writeServerHash(encryptedExtensions.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400640 if config.Bugs.PartialEncryptedExtensionsWithServerHello {
641 // The first byte has already been sent.
642 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()[1:])
643 } else {
644 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal())
645 }
Nick Harper728eed82016-07-07 17:36:52 -0700646
647 if hs.suite.flags&suitePSK == 0 {
648 if config.ClientAuth >= RequestClientCert {
David Benjamin8d343b42016-07-09 14:26:01 -0700649 // Request a client certificate
650 certReq := &certificateRequestMsg{
651 hasSignatureAlgorithm: true,
652 hasRequestContext: true,
David Benjamin8a8349b2016-08-18 02:32:23 -0400653 requestContext: config.Bugs.SendRequestContext,
David Benjamin8d343b42016-07-09 14:26:01 -0700654 }
655 if !config.Bugs.NoSignatureAlgorithms {
David Benjaminf74ec792016-07-13 21:18:49 -0400656 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin8d343b42016-07-09 14:26:01 -0700657 }
658
659 // An empty list of certificateAuthorities signals to
660 // the client that it may send any certificate in response
661 // to our request. When we know the CAs we trust, then
662 // we can send them down, so that the client can choose
663 // an appropriate certificate to give to us.
664 if config.ClientCAs != nil {
665 certReq.certificateAuthorities = config.ClientCAs.Subjects()
666 }
667 hs.writeServerHash(certReq.marshal())
668 c.writeRecord(recordTypeHandshake, certReq.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700669 }
670
671 certMsg := &certificateMsg{
672 hasRequestContext: true,
673 }
674 if !config.Bugs.EmptyCertificateList {
675 certMsg.certificates = hs.cert.Certificate
676 }
David Benjamin1edae6b2016-07-13 16:58:23 -0400677 certMsgBytes := certMsg.marshal()
David Benjamin1edae6b2016-07-13 16:58:23 -0400678 hs.writeServerHash(certMsgBytes)
679 c.writeRecord(recordTypeHandshake, certMsgBytes)
Nick Harper728eed82016-07-07 17:36:52 -0700680
681 certVerify := &certificateVerifyMsg{
682 hasSignatureAlgorithm: true,
683 }
684
685 // Determine the hash to sign.
686 privKey := hs.cert.PrivateKey
687
688 var err error
689 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, config, hs.clientHello.signatureAlgorithms)
690 if err != nil {
691 c.sendAlert(alertInternalError)
692 return err
693 }
694
695 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
696 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
697 if err != nil {
698 c.sendAlert(alertInternalError)
699 return err
700 }
701
Steven Valdez0ee2e112016-07-15 06:51:15 -0400702 if config.Bugs.SendSignatureAlgorithm != 0 {
703 certVerify.signatureAlgorithm = config.Bugs.SendSignatureAlgorithm
704 }
705
Nick Harper728eed82016-07-07 17:36:52 -0700706 hs.writeServerHash(certVerify.marshal())
707 c.writeRecord(recordTypeHandshake, certVerify.marshal())
Nick Harper0b3625b2016-07-25 16:16:28 -0700708 } else {
709 // Pick up certificates from the session instead.
710 // hs.sessionState may be nil if config.Bugs.EnableAllCiphers is
711 // true.
712 if hs.sessionState != nil && len(hs.sessionState.certificates) > 0 {
713 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
714 return err
715 }
716 }
Nick Harper728eed82016-07-07 17:36:52 -0700717 }
718
719 finished := new(finishedMsg)
720 finished.verifyData = hs.finishedHash.serverSum(handshakeTrafficSecret)
721 if config.Bugs.BadFinished {
722 finished.verifyData[0]++
723 }
724 hs.writeServerHash(finished.marshal())
725 c.writeRecord(recordTypeHandshake, finished.marshal())
David Benjamin02edcd02016-07-27 17:40:37 -0400726 if c.config.Bugs.SendExtraFinished {
727 c.writeRecord(recordTypeHandshake, finished.marshal())
728 }
Nick Harper728eed82016-07-07 17:36:52 -0700729 c.flushHandshake()
730
731 // The various secrets do not incorporate the client's final leg, so
732 // derive them now before updating the handshake context.
733 masterSecret := hs.finishedHash.extractKey(handshakeSecret, hs.finishedHash.zeroSecret())
734 trafficSecret := hs.finishedHash.deriveSecret(masterSecret, applicationTrafficLabel)
735
David Benjamin2aad4062016-07-14 23:15:40 -0400736 // Switch to application data keys on write. In particular, any alerts
737 // from the client certificate are sent over these keys.
David Benjamin21c00282016-07-18 21:56:23 +0200738 c.out.useTrafficSecret(c.vers, hs.suite, trafficSecret, applicationPhase, serverWrite)
David Benjamin2aad4062016-07-14 23:15:40 -0400739
Nick Harper728eed82016-07-07 17:36:52 -0700740 // If we requested a client certificate, then the client must send a
741 // certificate message, even if it's empty.
742 if config.ClientAuth >= RequestClientCert {
David Benjamin8d343b42016-07-09 14:26:01 -0700743 msg, err := c.readHandshake()
744 if err != nil {
745 return err
746 }
747
748 certMsg, ok := msg.(*certificateMsg)
749 if !ok {
750 c.sendAlert(alertUnexpectedMessage)
751 return unexpectedMessageError(certMsg, msg)
752 }
753 hs.writeClientHash(certMsg.marshal())
754
755 if len(certMsg.certificates) == 0 {
756 // The client didn't actually send a certificate
757 switch config.ClientAuth {
758 case RequireAnyClientCert, RequireAndVerifyClientCert:
759 c.sendAlert(alertBadCertificate)
760 return errors.New("tls: client didn't provide a certificate")
761 }
762 }
763
764 pub, err := hs.processCertsFromClient(certMsg.certificates)
765 if err != nil {
766 return err
767 }
768
769 if len(c.peerCertificates) > 0 {
770 msg, err = c.readHandshake()
771 if err != nil {
772 return err
773 }
774
775 certVerify, ok := msg.(*certificateVerifyMsg)
776 if !ok {
777 c.sendAlert(alertUnexpectedMessage)
778 return unexpectedMessageError(certVerify, msg)
779 }
780
David Benjaminf74ec792016-07-13 21:18:49 -0400781 c.peerSignatureAlgorithm = certVerify.signatureAlgorithm
David Benjamin8d343b42016-07-09 14:26:01 -0700782 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
783 if err := verifyMessage(c.vers, pub, config, certVerify.signatureAlgorithm, input, certVerify.signature); err != nil {
784 c.sendAlert(alertBadCertificate)
785 return err
786 }
787 hs.writeClientHash(certVerify.marshal())
788 }
Nick Harper728eed82016-07-07 17:36:52 -0700789 }
790
791 // Read the client Finished message.
792 msg, err := c.readHandshake()
793 if err != nil {
794 return err
795 }
796 clientFinished, ok := msg.(*finishedMsg)
797 if !ok {
798 c.sendAlert(alertUnexpectedMessage)
799 return unexpectedMessageError(clientFinished, msg)
800 }
801
802 verify := hs.finishedHash.clientSum(handshakeTrafficSecret)
803 if len(verify) != len(clientFinished.verifyData) ||
804 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
805 c.sendAlert(alertHandshakeFailure)
806 return errors.New("tls: client's Finished message was incorrect")
807 }
David Benjamin97a0a082016-07-13 17:57:35 -0400808 hs.writeClientHash(clientFinished.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700809
David Benjamin2aad4062016-07-14 23:15:40 -0400810 // Switch to application data keys on read.
David Benjamin21c00282016-07-18 21:56:23 +0200811 c.in.useTrafficSecret(c.vers, hs.suite, trafficSecret, applicationPhase, clientWrite)
Nick Harper728eed82016-07-07 17:36:52 -0700812
Nick Harper728eed82016-07-07 17:36:52 -0700813 c.cipherSuite = hs.suite
David Benjamin97a0a082016-07-13 17:57:35 -0400814 c.exporterSecret = hs.finishedHash.deriveSecret(masterSecret, exporterLabel)
David Benjamin58104882016-07-18 01:25:41 +0200815 c.resumptionSecret = hs.finishedHash.deriveSecret(masterSecret, resumptionLabel)
816
817 // TODO(davidben): Allow configuring the number of tickets sent for
818 // testing.
819 if !c.config.SessionTicketsDisabled {
820 ticketCount := 2
821 for i := 0; i < ticketCount; i++ {
822 c.SendNewSessionTicket()
823 }
824 }
Nick Harper728eed82016-07-07 17:36:52 -0700825 return nil
826}
827
David Benjaminf25dda92016-07-04 10:05:26 -0700828// processClientHello processes the ClientHello message from the client and
829// decides whether we will perform session resumption.
830func (hs *serverHandshakeState) processClientHello() (isResume bool, err error) {
831 config := hs.c.config
832 c := hs.c
833
834 hs.hello = &serverHelloMsg{
835 isDTLS: c.isDTLS,
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400836 vers: versionToWire(c.vers, c.isDTLS),
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400837 versOverride: config.Bugs.SendServerHelloVersion,
David Benjaminf25dda92016-07-04 10:05:26 -0700838 compressionMethod: compressionNone,
839 }
840
841 hs.hello.random = make([]byte, 32)
842 _, err = io.ReadFull(config.rand(), hs.hello.random)
843 if err != nil {
844 c.sendAlert(alertInternalError)
845 return false, err
846 }
David Benjamin1f61f0d2016-07-10 12:20:35 -0400847 // Signal downgrades in the server random, per draft-ietf-tls-tls13-14,
848 // section 6.3.1.2.
Nick Harper85f20c22016-07-04 10:11:59 -0700849 if c.vers <= VersionTLS12 && config.maxVersion(c.isDTLS) >= VersionTLS13 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400850 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS13)
Nick Harper85f20c22016-07-04 10:11:59 -0700851 }
852 if c.vers <= VersionTLS11 && config.maxVersion(c.isDTLS) == VersionTLS12 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400853 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS12)
Nick Harper85f20c22016-07-04 10:11:59 -0700854 }
David Benjaminf25dda92016-07-04 10:05:26 -0700855
856 foundCompression := false
857 // We only support null compression, so check that the client offered it.
858 for _, compression := range hs.clientHello.compressionMethods {
859 if compression == compressionNone {
860 foundCompression = true
861 break
862 }
863 }
864
865 if !foundCompression {
866 c.sendAlert(alertHandshakeFailure)
867 return false, errors.New("tls: client does not support uncompressed connections")
868 }
David Benjamin7d79f832016-07-04 09:20:45 -0700869
870 if err := hs.processClientExtensions(&hs.hello.extensions); err != nil {
871 return false, err
Adam Langley09505632015-07-30 18:10:13 -0700872 }
Adam Langley95c29f32014-06-20 12:00:00 -0700873
874 supportedCurve := false
875 preferredCurves := config.curvePreferences()
876Curves:
877 for _, curve := range hs.clientHello.supportedCurves {
878 for _, supported := range preferredCurves {
879 if supported == curve {
880 supportedCurve = true
881 break Curves
882 }
883 }
884 }
885
886 supportedPointFormat := false
887 for _, pointFormat := range hs.clientHello.supportedPoints {
888 if pointFormat == pointFormatUncompressed {
889 supportedPointFormat = true
890 break
891 }
892 }
893 hs.ellipticOk = supportedCurve && supportedPointFormat
894
Adam Langley95c29f32014-06-20 12:00:00 -0700895 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
896
David Benjamin4b27d9f2015-05-12 22:42:52 -0400897 // For test purposes, check that the peer never offers a session when
898 // renegotiating.
899 if c.cipherSuite != nil && len(hs.clientHello.sessionId) > 0 && c.config.Bugs.FailIfResumeOnRenego {
900 return false, errors.New("tls: offered resumption on renegotiation")
901 }
902
David Benjamindd6fed92015-10-23 17:41:12 -0400903 if c.config.Bugs.FailIfSessionOffered && (len(hs.clientHello.sessionTicket) > 0 || len(hs.clientHello.sessionId) > 0) {
904 return false, errors.New("tls: client offered a session ticket or ID")
905 }
906
Adam Langley95c29f32014-06-20 12:00:00 -0700907 if hs.checkForResumption() {
908 return true, nil
909 }
910
Adam Langley95c29f32014-06-20 12:00:00 -0700911 var preferenceList, supportedList []uint16
912 if c.config.PreferServerCipherSuites {
913 preferenceList = c.config.cipherSuites()
914 supportedList = hs.clientHello.cipherSuites
915 } else {
916 preferenceList = hs.clientHello.cipherSuites
917 supportedList = c.config.cipherSuites()
918 }
919
920 for _, id := range preferenceList {
Nick Harper728eed82016-07-07 17:36:52 -0700921 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk, true); hs.suite != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700922 break
923 }
924 }
925
926 if hs.suite == nil {
927 c.sendAlert(alertHandshakeFailure)
928 return false, errors.New("tls: no cipher suite supported by both client and server")
929 }
930
931 return false, nil
932}
933
David Benjamin7d79f832016-07-04 09:20:45 -0700934// processClientExtensions processes all ClientHello extensions not directly
935// related to cipher suite negotiation and writes responses in serverExtensions.
936func (hs *serverHandshakeState) processClientExtensions(serverExtensions *serverExtensions) error {
937 config := hs.c.config
938 c := hs.c
939
David Benjamin8d315d72016-07-18 01:03:18 +0200940 if c.vers < VersionTLS13 || config.Bugs.NegotiateRenegotiationInfoAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700941 if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) {
942 c.sendAlert(alertHandshakeFailure)
943 return errors.New("tls: renegotiation mismatch")
David Benjamin7d79f832016-07-04 09:20:45 -0700944 }
David Benjamin7d79f832016-07-04 09:20:45 -0700945
Nick Harper728eed82016-07-07 17:36:52 -0700946 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
947 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.clientVerify...)
948 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.serverVerify...)
949 if c.config.Bugs.BadRenegotiationInfo {
950 serverExtensions.secureRenegotiation[0] ^= 0x80
951 }
952 } else {
953 serverExtensions.secureRenegotiation = hs.clientHello.secureRenegotiation
954 }
955
956 if c.noRenegotiationInfo() {
957 serverExtensions.secureRenegotiation = nil
958 }
David Benjamin7d79f832016-07-04 09:20:45 -0700959 }
960
961 serverExtensions.duplicateExtension = c.config.Bugs.DuplicateExtension
962
963 if len(hs.clientHello.serverName) > 0 {
964 c.serverName = hs.clientHello.serverName
965 }
966 if len(config.Certificates) == 0 {
967 c.sendAlert(alertInternalError)
968 return errors.New("tls: no certificates configured")
969 }
970 hs.cert = &config.Certificates[0]
971 if len(hs.clientHello.serverName) > 0 {
972 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
973 }
974 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
975 return errors.New("tls: unexpected server name")
976 }
977
978 if len(hs.clientHello.alpnProtocols) > 0 {
979 if proto := c.config.Bugs.ALPNProtocol; proto != nil {
980 serverExtensions.alpnProtocol = *proto
981 serverExtensions.alpnProtocolEmpty = len(*proto) == 0
982 c.clientProtocol = *proto
983 c.usedALPN = true
984 } else if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
985 serverExtensions.alpnProtocol = selectedProto
986 c.clientProtocol = selectedProto
987 c.usedALPN = true
988 }
989 }
Nick Harper728eed82016-07-07 17:36:52 -0700990
David Benjamin0c40a962016-08-01 12:05:50 -0400991 if len(c.config.Bugs.SendALPN) > 0 {
992 serverExtensions.alpnProtocol = c.config.Bugs.SendALPN
993 }
994
David Benjamin8d315d72016-07-18 01:03:18 +0200995 if c.vers < VersionTLS13 || config.Bugs.NegotiateNPNAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700996 if len(hs.clientHello.alpnProtocols) == 0 || c.config.Bugs.NegotiateALPNAndNPN {
997 // Although sending an empty NPN extension is reasonable, Firefox has
998 // had a bug around this. Best to send nothing at all if
999 // config.NextProtos is empty. See
1000 // https://code.google.com/p/go/issues/detail?id=5445.
1001 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
1002 serverExtensions.nextProtoNeg = true
1003 serverExtensions.nextProtos = config.NextProtos
1004 serverExtensions.npnLast = config.Bugs.SwapNPNAndALPN
1005 }
David Benjamin7d79f832016-07-04 09:20:45 -07001006 }
Steven Valdez143e8b32016-07-11 13:19:03 -04001007 }
David Benjamin7d79f832016-07-04 09:20:45 -07001008
David Benjamin8d315d72016-07-18 01:03:18 +02001009 if c.vers < VersionTLS13 || config.Bugs.NegotiateEMSAtAllVersions {
David Benjamin163c9562016-08-29 23:14:17 -04001010 disableEMS := config.Bugs.NoExtendedMasterSecret
1011 if c.cipherSuite != nil {
1012 disableEMS = config.Bugs.NoExtendedMasterSecretOnRenegotiation
1013 }
1014 serverExtensions.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !disableEMS
Steven Valdez143e8b32016-07-11 13:19:03 -04001015 }
David Benjamin7d79f832016-07-04 09:20:45 -07001016
David Benjamin8d315d72016-07-18 01:03:18 +02001017 if c.vers < VersionTLS13 || config.Bugs.NegotiateChannelIDAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -07001018 if hs.clientHello.channelIDSupported && config.RequestChannelID {
1019 serverExtensions.channelIDRequested = true
1020 }
David Benjamin7d79f832016-07-04 09:20:45 -07001021 }
1022
1023 if hs.clientHello.srtpProtectionProfiles != nil {
1024 SRTPLoop:
1025 for _, p1 := range c.config.SRTPProtectionProfiles {
1026 for _, p2 := range hs.clientHello.srtpProtectionProfiles {
1027 if p1 == p2 {
1028 serverExtensions.srtpProtectionProfile = p1
1029 c.srtpProtectionProfile = p1
1030 break SRTPLoop
1031 }
1032 }
1033 }
1034 }
1035
1036 if c.config.Bugs.SendSRTPProtectionProfile != 0 {
1037 serverExtensions.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
1038 }
1039
1040 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
1041 if hs.clientHello.customExtension != *expected {
1042 return fmt.Errorf("tls: bad custom extension contents %q", hs.clientHello.customExtension)
1043 }
1044 }
1045 serverExtensions.customExtension = config.Bugs.CustomExtension
1046
Steven Valdez143e8b32016-07-11 13:19:03 -04001047 if c.config.Bugs.AdvertiseTicketExtension {
1048 serverExtensions.ticketSupported = true
1049 }
1050
David Benjamin65ac9972016-09-02 21:35:25 -04001051 if !hs.clientHello.hasGREASEExtension && config.Bugs.ExpectGREASE {
1052 return errors.New("tls: no GREASE extension found")
1053 }
1054
David Benjamin7d79f832016-07-04 09:20:45 -07001055 return nil
1056}
1057
Adam Langley95c29f32014-06-20 12:00:00 -07001058// checkForResumption returns true if we should perform resumption on this connection.
1059func (hs *serverHandshakeState) checkForResumption() bool {
1060 c := hs.c
1061
David Benjamin405da482016-08-08 17:25:07 -04001062 ticket := hs.clientHello.sessionTicket
1063 if len(ticket) == 0 && len(hs.clientHello.pskIdentities) > 0 && c.config.Bugs.AcceptAnySession {
1064 ticket = hs.clientHello.pskIdentities[0]
1065 }
1066 if len(ticket) > 0 {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001067 if c.config.SessionTicketsDisabled {
1068 return false
1069 }
David Benjaminb0c8db72014-09-24 15:19:56 -04001070
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001071 var ok bool
David Benjamin405da482016-08-08 17:25:07 -04001072 if hs.sessionState, ok = c.decryptTicket(ticket); !ok {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001073 return false
1074 }
1075 } else {
1076 if c.config.ServerSessionCache == nil {
1077 return false
1078 }
1079
1080 var ok bool
1081 sessionId := string(hs.clientHello.sessionId)
1082 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
1083 return false
1084 }
Adam Langley95c29f32014-06-20 12:00:00 -07001085 }
1086
David Benjamin405da482016-08-08 17:25:07 -04001087 if !c.config.Bugs.AcceptAnySession {
1088 // Never resume a session for a different SSL version.
1089 if c.vers != hs.sessionState.vers {
1090 return false
Adam Langley95c29f32014-06-20 12:00:00 -07001091 }
David Benjamin405da482016-08-08 17:25:07 -04001092
1093 cipherSuiteOk := false
1094 // Check that the client is still offering the ciphersuite in the session.
1095 for _, id := range hs.clientHello.cipherSuites {
1096 if id == hs.sessionState.cipherSuite {
1097 cipherSuiteOk = true
1098 break
1099 }
1100 }
1101 if !cipherSuiteOk {
1102 return false
1103 }
Adam Langley95c29f32014-06-20 12:00:00 -07001104 }
1105
1106 // Check that we also support the ciphersuite from the session.
Nick Harper728eed82016-07-07 17:36:52 -07001107 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 -07001108 if hs.suite == nil {
1109 return false
1110 }
1111
1112 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
1113 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
1114 if needClientCerts && !sessionHasClientCerts {
1115 return false
1116 }
1117 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
1118 return false
1119 }
1120
1121 return true
1122}
1123
1124func (hs *serverHandshakeState) doResumeHandshake() error {
1125 c := hs.c
1126
1127 hs.hello.cipherSuite = hs.suite.id
David Benjaminece3de92015-03-16 18:02:20 -04001128 if c.config.Bugs.SendCipherSuite != 0 {
1129 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
1130 }
Adam Langley95c29f32014-06-20 12:00:00 -07001131 // We echo the client's session ID in the ServerHello to let it know
1132 // that we're doing a resumption.
1133 hs.hello.sessionId = hs.clientHello.sessionId
Nick Harperb3d51be2016-07-01 11:43:18 -04001134 hs.hello.extensions.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -07001135
David Benjamin80d1b352016-05-04 19:19:06 -04001136 if c.config.Bugs.SendSCTListOnResume != nil {
Nick Harperb3d51be2016-07-01 11:43:18 -04001137 hs.hello.extensions.sctList = c.config.Bugs.SendSCTListOnResume
David Benjamin80d1b352016-05-04 19:19:06 -04001138 }
1139
Adam Langley95c29f32014-06-20 12:00:00 -07001140 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -04001141 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -04001142 hs.writeClientHash(hs.clientHello.marshal())
1143 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001144
1145 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
1146
1147 if len(hs.sessionState.certificates) > 0 {
1148 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
1149 return err
1150 }
1151 }
1152
1153 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -07001154 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -07001155
1156 return nil
1157}
1158
1159func (hs *serverHandshakeState) doFullHandshake() error {
1160 config := hs.c.config
1161 c := hs.c
1162
David Benjamin48cae082014-10-27 01:06:24 -04001163 isPSK := hs.suite.flags&suitePSK != 0
1164 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001165 hs.hello.extensions.ocspStapling = true
Adam Langley95c29f32014-06-20 12:00:00 -07001166 }
1167
David Benjamin61f95272014-11-25 01:55:35 -05001168 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001169 hs.hello.extensions.sctList = hs.cert.SignedCertificateTimestampList
David Benjamin61f95272014-11-25 01:55:35 -05001170 }
1171
Nick Harperb3d51be2016-07-01 11:43:18 -04001172 hs.hello.extensions.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
Adam Langley95c29f32014-06-20 12:00:00 -07001173 hs.hello.cipherSuite = hs.suite.id
David Benjamin6095de82014-12-27 01:50:38 -05001174 if config.Bugs.SendCipherSuite != 0 {
1175 hs.hello.cipherSuite = config.Bugs.SendCipherSuite
1176 }
Nick Harperb3d51be2016-07-01 11:43:18 -04001177 c.extendedMasterSecret = hs.hello.extensions.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -07001178
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001179 // Generate a session ID if we're to save the session.
Nick Harperb3d51be2016-07-01 11:43:18 -04001180 if !hs.hello.extensions.ticketSupported && config.ServerSessionCache != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001181 hs.hello.sessionId = make([]byte, 32)
1182 if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
1183 c.sendAlert(alertInternalError)
1184 return errors.New("tls: short read from Rand: " + err.Error())
1185 }
1186 }
1187
Adam Langley95c29f32014-06-20 12:00:00 -07001188 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -04001189 hs.writeClientHash(hs.clientHello.marshal())
1190 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001191
David Benjaminabe94e32016-09-04 14:18:58 -04001192 if config.Bugs.SendSNIWarningAlert {
1193 c.SendAlert(alertLevelWarning, alertUnrecognizedName)
1194 }
1195
Adam Langley95c29f32014-06-20 12:00:00 -07001196 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
1197
David Benjamin48cae082014-10-27 01:06:24 -04001198 if !isPSK {
1199 certMsg := new(certificateMsg)
David Benjamin8923c0b2015-06-07 11:42:34 -04001200 if !config.Bugs.EmptyCertificateList {
1201 certMsg.certificates = hs.cert.Certificate
1202 }
David Benjamin48cae082014-10-27 01:06:24 -04001203 if !config.Bugs.UnauthenticatedECDH {
David Benjaminbcb2d912015-02-24 23:45:43 -05001204 certMsgBytes := certMsg.marshal()
David Benjaminbcb2d912015-02-24 23:45:43 -05001205 hs.writeServerHash(certMsgBytes)
1206 c.writeRecord(recordTypeHandshake, certMsgBytes)
David Benjamin48cae082014-10-27 01:06:24 -04001207 }
David Benjamin1c375dd2014-07-12 00:48:23 -04001208 }
Adam Langley95c29f32014-06-20 12:00:00 -07001209
Nick Harperb3d51be2016-07-01 11:43:18 -04001210 if hs.hello.extensions.ocspStapling && !c.config.Bugs.SkipCertificateStatus {
Adam Langley95c29f32014-06-20 12:00:00 -07001211 certStatus := new(certificateStatusMsg)
1212 certStatus.statusType = statusTypeOCSP
1213 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -04001214 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001215 c.writeRecord(recordTypeHandshake, certStatus.marshal())
1216 }
1217
1218 keyAgreement := hs.suite.ka(c.vers)
1219 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
1220 if err != nil {
1221 c.sendAlert(alertHandshakeFailure)
1222 return err
1223 }
Steven Valdez5440fe02016-07-18 12:40:30 -04001224 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
1225 c.curveID = ecdhe.curveID
1226 }
David Benjamin9c651c92014-07-12 13:27:45 -04001227 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -04001228 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001229 c.writeRecord(recordTypeHandshake, skx.marshal())
1230 }
1231
1232 if config.ClientAuth >= RequestClientCert {
1233 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -04001234 certReq := &certificateRequestMsg{
1235 certificateTypes: config.ClientCertificateTypes,
1236 }
1237 if certReq.certificateTypes == nil {
1238 certReq.certificateTypes = []byte{
1239 byte(CertTypeRSASign),
1240 byte(CertTypeECDSASign),
1241 }
Adam Langley95c29f32014-06-20 12:00:00 -07001242 }
1243 if c.vers >= VersionTLS12 {
Nick Harper60edffd2016-06-21 15:19:24 -07001244 certReq.hasSignatureAlgorithm = true
1245 if !config.Bugs.NoSignatureAlgorithms {
David Benjamin7a41d372016-07-09 11:21:54 -07001246 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin000800a2014-11-14 01:43:59 -05001247 }
Adam Langley95c29f32014-06-20 12:00:00 -07001248 }
1249
1250 // An empty list of certificateAuthorities signals to
1251 // the client that it may send any certificate in response
1252 // to our request. When we know the CAs we trust, then
1253 // we can send them down, so that the client can choose
1254 // an appropriate certificate to give to us.
1255 if config.ClientCAs != nil {
1256 certReq.certificateAuthorities = config.ClientCAs.Subjects()
1257 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001258 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001259 c.writeRecord(recordTypeHandshake, certReq.marshal())
1260 }
1261
1262 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001263 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001264 c.writeRecord(recordTypeHandshake, helloDone.marshal())
David Benjamin582ba042016-07-07 12:33:25 -07001265 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001266
1267 var pub crypto.PublicKey // public key for client auth, if any
1268
David Benjamin83f90402015-01-27 01:09:43 -05001269 if err := c.simulatePacketLoss(nil); err != nil {
1270 return err
1271 }
Adam Langley95c29f32014-06-20 12:00:00 -07001272 msg, err := c.readHandshake()
1273 if err != nil {
1274 return err
1275 }
1276
1277 var ok bool
1278 // If we requested a client certificate, then the client must send a
1279 // certificate message, even if it's empty.
1280 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -04001281 var certMsg *certificateMsg
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001282 var certificates [][]byte
1283 if certMsg, ok = msg.(*certificateMsg); ok {
1284 if c.vers == VersionSSL30 && len(certMsg.certificates) == 0 {
1285 return errors.New("tls: empty certificate message in SSL 3.0")
1286 }
1287
1288 hs.writeClientHash(certMsg.marshal())
1289 certificates = certMsg.certificates
1290 } else if c.vers != VersionSSL30 {
1291 // In TLS, the Certificate message is required. In SSL
1292 // 3.0, the peer skips it when sending no certificates.
Adam Langley95c29f32014-06-20 12:00:00 -07001293 c.sendAlert(alertUnexpectedMessage)
1294 return unexpectedMessageError(certMsg, msg)
1295 }
Adam Langley95c29f32014-06-20 12:00:00 -07001296
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001297 if len(certificates) == 0 {
Adam Langley95c29f32014-06-20 12:00:00 -07001298 // The client didn't actually send a certificate
1299 switch config.ClientAuth {
1300 case RequireAnyClientCert, RequireAndVerifyClientCert:
1301 c.sendAlert(alertBadCertificate)
1302 return errors.New("tls: client didn't provide a certificate")
1303 }
1304 }
1305
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001306 pub, err = hs.processCertsFromClient(certificates)
Adam Langley95c29f32014-06-20 12:00:00 -07001307 if err != nil {
1308 return err
1309 }
1310
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001311 if ok {
1312 msg, err = c.readHandshake()
1313 if err != nil {
1314 return err
1315 }
Adam Langley95c29f32014-06-20 12:00:00 -07001316 }
1317 }
1318
1319 // Get client key exchange
1320 ckx, ok := msg.(*clientKeyExchangeMsg)
1321 if !ok {
1322 c.sendAlert(alertUnexpectedMessage)
1323 return unexpectedMessageError(ckx, msg)
1324 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001325 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001326
David Benjamine098ec22014-08-27 23:13:20 -04001327 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
1328 if err != nil {
1329 c.sendAlert(alertHandshakeFailure)
1330 return err
1331 }
Adam Langley75712922014-10-10 16:23:43 -07001332 if c.extendedMasterSecret {
1333 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1334 } else {
1335 if c.config.Bugs.RequireExtendedMasterSecret {
1336 return errors.New("tls: extended master secret required but not supported by peer")
1337 }
1338 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
1339 }
David Benjamine098ec22014-08-27 23:13:20 -04001340
Adam Langley95c29f32014-06-20 12:00:00 -07001341 // If we received a client cert in response to our certificate request message,
1342 // the client will send us a certificateVerifyMsg immediately after the
1343 // clientKeyExchangeMsg. This message is a digest of all preceding
1344 // handshake-layer messages that is signed using the private key corresponding
1345 // to the client's certificate. This allows us to verify that the client is in
1346 // possession of the private key of the certificate.
1347 if len(c.peerCertificates) > 0 {
1348 msg, err = c.readHandshake()
1349 if err != nil {
1350 return err
1351 }
1352 certVerify, ok := msg.(*certificateVerifyMsg)
1353 if !ok {
1354 c.sendAlert(alertUnexpectedMessage)
1355 return unexpectedMessageError(certVerify, msg)
1356 }
1357
David Benjaminde620d92014-07-18 15:03:41 -04001358 // Determine the signature type.
Nick Harper60edffd2016-06-21 15:19:24 -07001359 var sigAlg signatureAlgorithm
1360 if certVerify.hasSignatureAlgorithm {
1361 sigAlg = certVerify.signatureAlgorithm
Nick Harper60edffd2016-06-21 15:19:24 -07001362 c.peerSignatureAlgorithm = sigAlg
David Benjaminde620d92014-07-18 15:03:41 -04001363 }
1364
Nick Harper60edffd2016-06-21 15:19:24 -07001365 if c.vers > VersionSSL30 {
David Benjamin1fb125c2016-07-08 18:52:12 -07001366 err = verifyMessage(c.vers, pub, c.config, sigAlg, hs.finishedHash.buffer, certVerify.signature)
Nick Harper60edffd2016-06-21 15:19:24 -07001367 } else {
1368 // SSL 3.0's client certificate construction is
1369 // incompatible with signatureAlgorithm.
1370 rsaPub, ok := pub.(*rsa.PublicKey)
1371 if !ok {
1372 err = errors.New("unsupported key type for client certificate")
1373 } else {
1374 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
1375 err = rsa.VerifyPKCS1v15(rsaPub, crypto.MD5SHA1, digest, certVerify.signature)
David Benjaminde620d92014-07-18 15:03:41 -04001376 }
Adam Langley95c29f32014-06-20 12:00:00 -07001377 }
1378 if err != nil {
1379 c.sendAlert(alertBadCertificate)
1380 return errors.New("could not validate signature of connection nonces: " + err.Error())
1381 }
1382
David Benjamin83c0bc92014-08-04 01:23:53 -04001383 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001384 }
1385
David Benjamine098ec22014-08-27 23:13:20 -04001386 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001387
1388 return nil
1389}
1390
1391func (hs *serverHandshakeState) establishKeys() error {
1392 c := hs.c
1393
1394 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001395 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 -07001396
1397 var clientCipher, serverCipher interface{}
1398 var clientHash, serverHash macFunction
1399
1400 if hs.suite.aead == nil {
1401 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
1402 clientHash = hs.suite.mac(c.vers, clientMAC)
1403 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
1404 serverHash = hs.suite.mac(c.vers, serverMAC)
1405 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001406 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1407 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001408 }
1409
1410 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
1411 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
1412
1413 return nil
1414}
1415
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001416func (hs *serverHandshakeState) readFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001417 c := hs.c
1418
1419 c.readRecord(recordTypeChangeCipherSpec)
1420 if err := c.in.error(); err != nil {
1421 return err
1422 }
1423
Nick Harperb3d51be2016-07-01 11:43:18 -04001424 if hs.hello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001425 msg, err := c.readHandshake()
1426 if err != nil {
1427 return err
1428 }
1429 nextProto, ok := msg.(*nextProtoMsg)
1430 if !ok {
1431 c.sendAlert(alertUnexpectedMessage)
1432 return unexpectedMessageError(nextProto, msg)
1433 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001434 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001435 c.clientProtocol = nextProto.proto
1436 }
1437
Nick Harperb3d51be2016-07-01 11:43:18 -04001438 if hs.hello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001439 msg, err := c.readHandshake()
1440 if err != nil {
1441 return err
1442 }
David Benjamin24599a82016-06-30 18:56:53 -04001443 channelIDMsg, ok := msg.(*channelIDMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001444 if !ok {
1445 c.sendAlert(alertUnexpectedMessage)
David Benjamin24599a82016-06-30 18:56:53 -04001446 return unexpectedMessageError(channelIDMsg, msg)
David Benjamind30a9902014-08-24 01:44:23 -04001447 }
David Benjamin24599a82016-06-30 18:56:53 -04001448 x := new(big.Int).SetBytes(channelIDMsg.channelID[0:32])
1449 y := new(big.Int).SetBytes(channelIDMsg.channelID[32:64])
1450 r := new(big.Int).SetBytes(channelIDMsg.channelID[64:96])
1451 s := new(big.Int).SetBytes(channelIDMsg.channelID[96:128])
David Benjamind30a9902014-08-24 01:44:23 -04001452 if !elliptic.P256().IsOnCurve(x, y) {
1453 return errors.New("tls: invalid channel ID public key")
1454 }
1455 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
1456 var resumeHash []byte
1457 if isResume {
1458 resumeHash = hs.sessionState.handshakeHash
1459 }
1460 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
1461 return errors.New("tls: invalid channel ID signature")
1462 }
1463 c.channelID = channelID
1464
David Benjamin24599a82016-06-30 18:56:53 -04001465 hs.writeClientHash(channelIDMsg.marshal())
David Benjamind30a9902014-08-24 01:44:23 -04001466 }
1467
Adam Langley95c29f32014-06-20 12:00:00 -07001468 msg, err := c.readHandshake()
1469 if err != nil {
1470 return err
1471 }
1472 clientFinished, ok := msg.(*finishedMsg)
1473 if !ok {
1474 c.sendAlert(alertUnexpectedMessage)
1475 return unexpectedMessageError(clientFinished, msg)
1476 }
1477
1478 verify := hs.finishedHash.clientSum(hs.masterSecret)
1479 if len(verify) != len(clientFinished.verifyData) ||
1480 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
1481 c.sendAlert(alertHandshakeFailure)
1482 return errors.New("tls: client's Finished message is incorrect")
1483 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001484 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001485 copy(out, clientFinished.verifyData)
Adam Langley95c29f32014-06-20 12:00:00 -07001486
David Benjamin83c0bc92014-08-04 01:23:53 -04001487 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001488 return nil
1489}
1490
1491func (hs *serverHandshakeState) sendSessionTicket() error {
Adam Langley95c29f32014-06-20 12:00:00 -07001492 c := hs.c
Adam Langley95c29f32014-06-20 12:00:00 -07001493 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -04001494 vers: c.vers,
1495 cipherSuite: hs.suite.id,
1496 masterSecret: hs.masterSecret,
1497 certificates: hs.certsFromClient,
1498 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -07001499 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001500
Nick Harperb3d51be2016-07-01 11:43:18 -04001501 if !hs.hello.extensions.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001502 if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
1503 c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
1504 }
1505 return nil
1506 }
1507
1508 m := new(newSessionTicketMsg)
1509
David Benjamindd6fed92015-10-23 17:41:12 -04001510 if !c.config.Bugs.SendEmptySessionTicket {
1511 var err error
1512 m.ticket, err = c.encryptTicket(&state)
1513 if err != nil {
1514 return err
1515 }
Adam Langley95c29f32014-06-20 12:00:00 -07001516 }
Adam Langley95c29f32014-06-20 12:00:00 -07001517
David Benjamin83c0bc92014-08-04 01:23:53 -04001518 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001519 c.writeRecord(recordTypeHandshake, m.marshal())
1520
1521 return nil
1522}
1523
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001524func (hs *serverHandshakeState) sendFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001525 c := hs.c
1526
David Benjamin86271ee2014-07-21 16:14:03 -04001527 finished := new(finishedMsg)
1528 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001529 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001530 if c.config.Bugs.BadFinished {
1531 finished.verifyData[0]++
1532 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001533 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001534 hs.finishedBytes = finished.marshal()
1535 hs.writeServerHash(hs.finishedBytes)
1536 postCCSBytes := hs.finishedBytes
David Benjamin86271ee2014-07-21 16:14:03 -04001537
1538 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
1539 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
1540 postCCSBytes = postCCSBytes[5:]
David Benjamin61672812016-07-14 23:10:43 -04001541 } else if c.config.Bugs.SendUnencryptedFinished {
1542 c.writeRecord(recordTypeHandshake, postCCSBytes)
1543 postCCSBytes = nil
David Benjamin86271ee2014-07-21 16:14:03 -04001544 }
David Benjamin582ba042016-07-07 12:33:25 -07001545 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001546
David Benjamina0e52232014-07-19 17:39:58 -04001547 if !c.config.Bugs.SkipChangeCipherSpec {
David Benjamin8411b242015-11-26 12:07:28 -05001548 ccs := []byte{1}
1549 if c.config.Bugs.BadChangeCipherSpec != nil {
1550 ccs = c.config.Bugs.BadChangeCipherSpec
1551 }
1552 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamina0e52232014-07-19 17:39:58 -04001553 }
Adam Langley95c29f32014-06-20 12:00:00 -07001554
David Benjamin4189bd92015-01-25 23:52:39 -05001555 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1556 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1557 }
David Benjamindc3da932015-03-12 15:09:02 -04001558 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1559 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1560 return errors.New("tls: simulating post-CCS alert")
1561 }
David Benjamin4189bd92015-01-25 23:52:39 -05001562
David Benjamin61672812016-07-14 23:10:43 -04001563 if !c.config.Bugs.SkipFinished && len(postCCSBytes) > 0 {
David Benjaminb80168e2015-02-08 18:30:14 -05001564 c.writeRecord(recordTypeHandshake, postCCSBytes)
David Benjamin02edcd02016-07-27 17:40:37 -04001565 if c.config.Bugs.SendExtraFinished {
1566 c.writeRecord(recordTypeHandshake, finished.marshal())
1567 }
1568
David Benjamin12d2c482016-07-24 10:56:51 -04001569 if !c.config.Bugs.PackHelloRequestWithFinished {
1570 // Defer flushing until renegotiation.
1571 c.flushHandshake()
1572 }
David Benjaminb3774b92015-01-31 17:16:01 -05001573 }
Adam Langley95c29f32014-06-20 12:00:00 -07001574
David Benjaminc565ebb2015-04-03 04:06:36 -04001575 c.cipherSuite = hs.suite
Adam Langley95c29f32014-06-20 12:00:00 -07001576
1577 return nil
1578}
1579
1580// processCertsFromClient takes a chain of client certificates either from a
1581// Certificates message or from a sessionState and verifies them. It returns
1582// the public key of the leaf certificate.
1583func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
1584 c := hs.c
1585
1586 hs.certsFromClient = certificates
1587 certs := make([]*x509.Certificate, len(certificates))
1588 var err error
1589 for i, asn1Data := range certificates {
1590 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
1591 c.sendAlert(alertBadCertificate)
1592 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
1593 }
1594 }
1595
1596 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
1597 opts := x509.VerifyOptions{
1598 Roots: c.config.ClientCAs,
1599 CurrentTime: c.config.time(),
1600 Intermediates: x509.NewCertPool(),
1601 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
1602 }
1603
1604 for _, cert := range certs[1:] {
1605 opts.Intermediates.AddCert(cert)
1606 }
1607
1608 chains, err := certs[0].Verify(opts)
1609 if err != nil {
1610 c.sendAlert(alertBadCertificate)
1611 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
1612 }
1613
1614 ok := false
1615 for _, ku := range certs[0].ExtKeyUsage {
1616 if ku == x509.ExtKeyUsageClientAuth {
1617 ok = true
1618 break
1619 }
1620 }
1621 if !ok {
1622 c.sendAlert(alertHandshakeFailure)
1623 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
1624 }
1625
1626 c.verifiedChains = chains
1627 }
1628
1629 if len(certs) > 0 {
1630 var pub crypto.PublicKey
1631 switch key := certs[0].PublicKey.(type) {
1632 case *ecdsa.PublicKey, *rsa.PublicKey:
1633 pub = key
1634 default:
1635 c.sendAlert(alertUnsupportedCertificate)
1636 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
1637 }
1638 c.peerCertificates = certs
1639 return pub, nil
1640 }
1641
1642 return nil, nil
1643}
1644
David Benjamin83c0bc92014-08-04 01:23:53 -04001645func (hs *serverHandshakeState) writeServerHash(msg []byte) {
1646 // writeServerHash is called before writeRecord.
1647 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1648}
1649
1650func (hs *serverHandshakeState) writeClientHash(msg []byte) {
1651 // writeClientHash is called after readHandshake.
1652 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1653}
1654
1655func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
1656 if hs.c.isDTLS {
1657 // This is somewhat hacky. DTLS hashes a slightly different format.
1658 // First, the TLS header.
1659 hs.finishedHash.Write(msg[:4])
1660 // Then the sequence number and reassembled fragment offset (always 0).
1661 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1662 // Then the reassembled fragment (always equal to the message length).
1663 hs.finishedHash.Write(msg[1:4])
1664 // And then the message body.
1665 hs.finishedHash.Write(msg[4:])
1666 } else {
1667 hs.finishedHash.Write(msg)
1668 }
1669}
1670
Adam Langley95c29f32014-06-20 12:00:00 -07001671// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
1672// is acceptable to use.
Nick Harper728eed82016-07-07 17:36:52 -07001673func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk, pskOk bool) *cipherSuite {
Adam Langley95c29f32014-06-20 12:00:00 -07001674 for _, supported := range supportedCipherSuites {
1675 if id == supported {
1676 var candidate *cipherSuite
1677
1678 for _, s := range cipherSuites {
1679 if s.id == id {
1680 candidate = s
1681 break
1682 }
1683 }
1684 if candidate == nil {
1685 continue
1686 }
1687 // Don't select a ciphersuite which we can't
1688 // support for this client.
David Benjamin0407e762016-06-17 16:41:18 -04001689 if !c.config.Bugs.EnableAllCiphers {
Nick Harper728eed82016-07-07 17:36:52 -07001690 if (candidate.flags&suitePSK != 0) && !pskOk {
1691 continue
1692 }
David Benjamin0407e762016-06-17 16:41:18 -04001693 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
1694 continue
1695 }
1696 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
1697 continue
1698 }
1699 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
1700 continue
1701 }
Nick Harper728eed82016-07-07 17:36:52 -07001702 if version >= VersionTLS13 && candidate.flags&suiteTLS13 == 0 {
1703 continue
1704 }
David Benjamin0407e762016-06-17 16:41:18 -04001705 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
1706 continue
1707 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001708 }
Adam Langley95c29f32014-06-20 12:00:00 -07001709 return candidate
1710 }
1711 }
1712
1713 return nil
1714}
David Benjaminf93995b2015-11-05 18:23:20 -05001715
1716func isTLS12Cipher(id uint16) bool {
1717 for _, cipher := range cipherSuites {
1718 if cipher.id != id {
1719 continue
1720 }
1721 return cipher.flags&suiteTLS12 != 0
1722 }
1723 // Unknown cipher.
1724 return false
1725}
David Benjamin65ac9972016-09-02 21:35:25 -04001726
1727func isGREASEValue(val uint16) bool {
David Benjamin3c6a1ea2016-09-26 18:30:05 -04001728 return val&0x0f0f == 0x0a0a && val&0xff == val>>8
David Benjamin65ac9972016-09-02 21:35:25 -04001729}