blob: c2fae5571c89f79bd2bd36e986d3c48be4f48ec4 [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 }
Steven Valdezfdd10992016-09-15 16:27:05 -0400207
David Benjaminc44b1df2014-11-23 12:11:01 -0500208 c.clientVersion = hs.clientHello.vers
Steven Valdezfdd10992016-09-15 16:27:05 -0400209
210 // Convert the ClientHello wire version to a protocol version.
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400211 var clientVersion uint16
212 if c.isDTLS {
213 if hs.clientHello.vers <= 0xfefd {
214 clientVersion = VersionTLS12
215 } else if hs.clientHello.vers <= 0xfeff {
216 clientVersion = VersionTLS10
217 }
218 } else {
Steven Valdezfdd10992016-09-15 16:27:05 -0400219 if hs.clientHello.vers >= VersionTLS12 {
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400220 clientVersion = VersionTLS12
221 } else if hs.clientHello.vers >= VersionTLS11 {
222 clientVersion = VersionTLS11
223 } else if hs.clientHello.vers >= VersionTLS10 {
224 clientVersion = VersionTLS10
225 } else if hs.clientHello.vers >= VersionSSL30 {
226 clientVersion = VersionSSL30
227 }
228 }
229
230 if config.Bugs.NegotiateVersion != 0 {
231 c.vers = config.Bugs.NegotiateVersion
232 } else if c.haveVers && config.Bugs.NegotiateVersionOnRenego != 0 {
233 c.vers = config.Bugs.NegotiateVersionOnRenego
Steven Valdezfdd10992016-09-15 16:27:05 -0400234 } else if len(hs.clientHello.supportedVersions) > 0 {
235 // Use the versions extension if supplied.
David Benjamind9791bf2016-09-27 16:39:52 -0400236 var foundVersion, foundGREASE bool
Steven Valdezfdd10992016-09-15 16:27:05 -0400237 for _, extVersion := range hs.clientHello.supportedVersions {
David Benjamind9791bf2016-09-27 16:39:52 -0400238 if isGREASEValue(extVersion) {
239 foundGREASE = true
240 }
Steven Valdezfdd10992016-09-15 16:27:05 -0400241 extVersion, ok = wireToVersion(extVersion, c.isDTLS)
242 if !ok {
243 continue
244 }
David Benjamind9791bf2016-09-27 16:39:52 -0400245 if config.isSupportedVersion(extVersion, c.isDTLS) && !foundVersion {
Steven Valdezfdd10992016-09-15 16:27:05 -0400246 c.vers = extVersion
247 foundVersion = true
248 break
249 }
250 }
251 if !foundVersion {
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400252 c.sendAlert(alertProtocolVersion)
Steven Valdezfdd10992016-09-15 16:27:05 -0400253 return errors.New("tls: client did not offer any supported protocol versions")
254 }
David Benjamind9791bf2016-09-27 16:39:52 -0400255 if config.Bugs.ExpectGREASE && !foundGREASE {
256 return errors.New("tls: no GREASE version value found")
257 }
Steven Valdezfdd10992016-09-15 16:27:05 -0400258 } else {
259 // Otherwise, use the legacy ClientHello version.
260 version := clientVersion
261 if maxVersion := config.maxVersion(c.isDTLS); version > maxVersion {
262 version = maxVersion
263 }
264 if version == 0 || !config.isSupportedVersion(version, c.isDTLS) {
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400265 return fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
266 }
Steven Valdezfdd10992016-09-15 16:27:05 -0400267 c.vers = version
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400268 }
269 c.haveVers = true
David Benjaminc44b1df2014-11-23 12:11:01 -0500270
David Benjamin6ae7f072015-01-26 10:22:13 -0500271 // Reject < 1.2 ClientHellos with signature_algorithms.
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400272 if clientVersion < VersionTLS12 && len(hs.clientHello.signatureAlgorithms) > 0 {
David Benjaminf25dda92016-07-04 10:05:26 -0700273 return fmt.Errorf("tls: client included signature_algorithms before TLS 1.2")
David Benjamin72dc7832015-03-16 17:49:43 -0400274 }
David Benjamin6ae7f072015-01-26 10:22:13 -0500275
David Benjaminf93995b2015-11-05 18:23:20 -0500276 // Check the client cipher list is consistent with the version.
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400277 if clientVersion < VersionTLS12 {
David Benjaminf93995b2015-11-05 18:23:20 -0500278 for _, id := range hs.clientHello.cipherSuites {
279 if isTLS12Cipher(id) {
David Benjaminf25dda92016-07-04 10:05:26 -0700280 return fmt.Errorf("tls: client offered TLS 1.2 cipher before TLS 1.2")
David Benjaminf93995b2015-11-05 18:23:20 -0500281 }
282 }
283 }
284
David Benjamin405da482016-08-08 17:25:07 -0400285 if config.Bugs.ExpectNoTLS12Session {
286 if len(hs.clientHello.sessionId) > 0 {
287 return fmt.Errorf("tls: client offered an unexpected session ID")
288 }
289 if len(hs.clientHello.sessionTicket) > 0 {
290 return fmt.Errorf("tls: client offered an unexpected session ticket")
291 }
292 }
293
294 if config.Bugs.ExpectNoTLS13PSK && len(hs.clientHello.pskIdentities) > 0 {
295 return fmt.Errorf("tls: client offered unexpected PSK identities")
296 }
297
David Benjamin65ac9972016-09-02 21:35:25 -0400298 var scsvFound, greaseFound bool
David Benjaminf25dda92016-07-04 10:05:26 -0700299 for _, cipherSuite := range hs.clientHello.cipherSuites {
300 if cipherSuite == fallbackSCSV {
301 scsvFound = true
David Benjamin65ac9972016-09-02 21:35:25 -0400302 }
303 if isGREASEValue(cipherSuite) {
304 greaseFound = true
David Benjaminf25dda92016-07-04 10:05:26 -0700305 }
306 }
307
308 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
309 return errors.New("tls: no fallback SCSV found when expected")
310 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
311 return errors.New("tls: fallback SCSV found when not expected")
312 }
313
David Benjamin65ac9972016-09-02 21:35:25 -0400314 if !greaseFound && config.Bugs.ExpectGREASE {
315 return errors.New("tls: no GREASE cipher suite value found")
316 }
317
318 greaseFound = false
319 for _, curve := range hs.clientHello.supportedCurves {
320 if isGREASEValue(uint16(curve)) {
321 greaseFound = true
322 break
323 }
324 }
325
326 if !greaseFound && config.Bugs.ExpectGREASE {
327 return errors.New("tls: no GREASE curve value found")
328 }
329
330 if len(hs.clientHello.keyShares) > 0 {
331 greaseFound = false
332 for _, keyShare := range hs.clientHello.keyShares {
333 if isGREASEValue(uint16(keyShare.group)) {
334 greaseFound = true
335 break
336 }
337 }
338
339 if !greaseFound && config.Bugs.ExpectGREASE {
340 return errors.New("tls: no GREASE curve value found")
341 }
342 }
343
David Benjaminf25dda92016-07-04 10:05:26 -0700344 if config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
David Benjamin7a41d372016-07-09 11:21:54 -0700345 hs.clientHello.signatureAlgorithms = config.signSignatureAlgorithms()
David Benjaminf25dda92016-07-04 10:05:26 -0700346 }
347 if config.Bugs.IgnorePeerCurvePreferences {
348 hs.clientHello.supportedCurves = config.curvePreferences()
349 }
350 if config.Bugs.IgnorePeerCipherPreferences {
351 hs.clientHello.cipherSuites = config.cipherSuites()
352 }
353
354 return nil
355}
356
Nick Harper728eed82016-07-07 17:36:52 -0700357func (hs *serverHandshakeState) doTLS13Handshake() error {
358 c := hs.c
359 config := c.config
360
361 hs.hello = &serverHelloMsg{
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400362 isDTLS: c.isDTLS,
363 vers: versionToWire(c.vers, c.isDTLS),
364 versOverride: config.Bugs.SendServerHelloVersion,
Steven Valdez5440fe02016-07-18 12:40:30 -0400365 }
366
Nick Harper728eed82016-07-07 17:36:52 -0700367 hs.hello.random = make([]byte, 32)
368 if _, err := io.ReadFull(config.rand(), hs.hello.random); err != nil {
369 c.sendAlert(alertInternalError)
370 return err
371 }
372
373 // TLS 1.3 forbids clients from advertising any non-null compression.
374 if len(hs.clientHello.compressionMethods) != 1 || hs.clientHello.compressionMethods[0] != compressionNone {
375 return errors.New("tls: client sent compression method other than null for TLS 1.3")
376 }
377
378 // Prepare an EncryptedExtensions message, but do not send it yet.
379 encryptedExtensions := new(encryptedExtensionsMsg)
Steven Valdez143e8b32016-07-11 13:19:03 -0400380 encryptedExtensions.empty = config.Bugs.EmptyEncryptedExtensions
Nick Harper728eed82016-07-07 17:36:52 -0700381 if err := hs.processClientExtensions(&encryptedExtensions.extensions); err != nil {
382 return err
383 }
384
385 supportedCurve := false
386 var selectedCurve CurveID
387 preferredCurves := config.curvePreferences()
388Curves:
389 for _, curve := range hs.clientHello.supportedCurves {
390 for _, supported := range preferredCurves {
391 if supported == curve {
392 supportedCurve = true
393 selectedCurve = curve
394 break Curves
395 }
396 }
397 }
398
Steven Valdez803c77a2016-09-06 14:13:43 -0400399 if !supportedCurve {
400 c.sendAlert(alertHandshakeFailure)
401 return errors.New("tls: no curve supported by both client and server")
402 }
Nick Harper728eed82016-07-07 17:36:52 -0700403
David Benjamin405da482016-08-08 17:25:07 -0400404 pskIdentities := hs.clientHello.pskIdentities
405 if len(pskIdentities) == 0 && len(hs.clientHello.sessionTicket) > 0 && c.config.Bugs.AcceptAnySession {
Steven Valdez5b986082016-09-01 12:29:49 -0400406 psk := pskIdentity{
407 keModes: []byte{pskDHEKEMode},
408 authModes: []byte{pskAuthMode},
409 ticket: hs.clientHello.sessionTicket,
410 }
411 pskIdentities = []pskIdentity{psk}
David Benjamin405da482016-08-08 17:25:07 -0400412 }
413 for i, pskIdentity := range pskIdentities {
Steven Valdez5b986082016-09-01 12:29:49 -0400414 foundKE := false
415 foundAuth := false
416
417 for _, keMode := range pskIdentity.keModes {
418 if keMode == pskDHEKEMode {
419 foundKE = true
420 }
421 }
422
423 for _, authMode := range pskIdentity.authModes {
424 if authMode == pskAuthMode {
425 foundAuth = true
426 }
427 }
428
429 if !foundKE || !foundAuth {
430 continue
431 }
432
433 sessionState, ok := c.decryptTicket(pskIdentity.ticket)
Nick Harper0b3625b2016-07-25 16:16:28 -0700434 if !ok {
435 continue
436 }
Steven Valdez803c77a2016-09-06 14:13:43 -0400437 if config.Bugs.AcceptAnySession {
438 // Replace the cipher suite with one known to work, to
439 // test cross-version resumption attempts.
440 sessionState.cipherSuite = TLS_AES_128_GCM_SHA256
441 } else {
David Benjamin405da482016-08-08 17:25:07 -0400442 if sessionState.vers != c.vers && c.config.Bugs.AcceptAnySession {
443 continue
444 }
David Benjamin405da482016-08-08 17:25:07 -0400445 if sessionState.ticketExpiration.Before(c.config.time()) {
446 continue
447 }
David Benjamin405da482016-08-08 17:25:07 -0400448
Steven Valdez803c77a2016-09-06 14:13:43 -0400449 cipherSuiteOk := false
450 // Check that the client is still offering the ciphersuite in the session.
451 for _, id := range hs.clientHello.cipherSuites {
452 if id == sessionState.cipherSuite {
453 cipherSuiteOk = true
454 break
455 }
456 }
457 if !cipherSuiteOk {
458 continue
Nick Harper0b3625b2016-07-25 16:16:28 -0700459 }
460 }
David Benjamin405da482016-08-08 17:25:07 -0400461
Steven Valdez803c77a2016-09-06 14:13:43 -0400462 // Check that we also support the ciphersuite from the session.
463 suite := c.tryCipherSuite(sessionState.cipherSuite, c.config.cipherSuites(), c.vers, true, true)
464 if suite == nil {
465 continue
Nick Harper0b3625b2016-07-25 16:16:28 -0700466 }
Steven Valdez803c77a2016-09-06 14:13:43 -0400467
468 hs.sessionState = sessionState
469 hs.suite = suite
470 hs.hello.hasPSKIdentity = true
471 hs.hello.pskIdentity = uint16(i)
472 c.didResume = true
473 break
Nick Harper728eed82016-07-07 17:36:52 -0700474 }
475
Nick Harper0b3625b2016-07-25 16:16:28 -0700476 // If not resuming, select the cipher suite.
477 if hs.suite == nil {
478 var preferenceList, supportedList []uint16
479 if config.PreferServerCipherSuites {
480 preferenceList = config.cipherSuites()
481 supportedList = hs.clientHello.cipherSuites
482 } else {
483 preferenceList = hs.clientHello.cipherSuites
484 supportedList = config.cipherSuites()
485 }
486
487 for _, id := range preferenceList {
Steven Valdez803c77a2016-09-06 14:13:43 -0400488 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, true, true); hs.suite != nil {
Nick Harper0b3625b2016-07-25 16:16:28 -0700489 break
490 }
Nick Harper728eed82016-07-07 17:36:52 -0700491 }
492 }
493
494 if hs.suite == nil {
495 c.sendAlert(alertHandshakeFailure)
496 return errors.New("tls: no cipher suite supported by both client and server")
497 }
498
499 hs.hello.cipherSuite = hs.suite.id
Steven Valdez0ee2e112016-07-15 06:51:15 -0400500 if c.config.Bugs.SendCipherSuite != 0 {
501 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
502 }
503
Nick Harper728eed82016-07-07 17:36:52 -0700504 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
505 hs.finishedHash.discardHandshakeBuffer()
506 hs.writeClientHash(hs.clientHello.marshal())
507
Steven Valdez803c77a2016-09-06 14:13:43 -0400508 hs.hello.useCertAuth = hs.sessionState == nil
509
Nick Harper728eed82016-07-07 17:36:52 -0700510 // Resolve PSK and compute the early secret.
Nick Harper0b3625b2016-07-25 16:16:28 -0700511 var psk []byte
Steven Valdez803c77a2016-09-06 14:13:43 -0400512 if hs.sessionState != nil {
Nick Harper0b3625b2016-07-25 16:16:28 -0700513 psk = deriveResumptionPSK(hs.suite, hs.sessionState.masterSecret)
514 hs.finishedHash.setResumptionContext(deriveResumptionContext(hs.suite, hs.sessionState.masterSecret))
515 } else {
516 psk = hs.finishedHash.zeroSecret()
517 hs.finishedHash.setResumptionContext(hs.finishedHash.zeroSecret())
518 }
Nick Harper728eed82016-07-07 17:36:52 -0700519
520 earlySecret := hs.finishedHash.extractKey(hs.finishedHash.zeroSecret(), psk)
521
Steven Valdez803c77a2016-09-06 14:13:43 -0400522 if config.Bugs.OmitServerHelloSignatureAlgorithms {
523 hs.hello.useCertAuth = false
524 } else if config.Bugs.IncludeServerHelloSignatureAlgorithms {
525 hs.hello.useCertAuth = true
526 }
527
528 hs.hello.hasKeyShare = true
529 if hs.sessionState != nil && config.Bugs.NegotiatePSKResumption {
530 hs.hello.hasKeyShare = false
531 }
532 if config.Bugs.MissingKeyShare {
533 hs.hello.hasKeyShare = false
534 }
535
Nick Harper728eed82016-07-07 17:36:52 -0700536 // Resolve ECDHE and compute the handshake secret.
537 var ecdheSecret []byte
Steven Valdez803c77a2016-09-06 14:13:43 -0400538 if hs.hello.hasKeyShare {
Nick Harper728eed82016-07-07 17:36:52 -0700539 // Look for the key share corresponding to our selected curve.
540 var selectedKeyShare *keyShareEntry
541 for i := range hs.clientHello.keyShares {
542 if hs.clientHello.keyShares[i].group == selectedCurve {
543 selectedKeyShare = &hs.clientHello.keyShares[i]
544 break
545 }
546 }
547
David Benjamine73c7f42016-08-17 00:29:33 -0400548 if config.Bugs.ExpectMissingKeyShare && selectedKeyShare != nil {
549 return errors.New("tls: expected missing key share")
550 }
551
Steven Valdez5440fe02016-07-18 12:40:30 -0400552 sendHelloRetryRequest := selectedKeyShare == nil
553 if config.Bugs.UnnecessaryHelloRetryRequest {
554 sendHelloRetryRequest = true
555 }
556 if config.Bugs.SkipHelloRetryRequest {
557 sendHelloRetryRequest = false
558 }
559 if sendHelloRetryRequest {
560 firstTime := true
561 ResendHelloRetryRequest:
Nick Harperdcfbc672016-07-16 17:47:31 +0200562 // Send HelloRetryRequest.
563 helloRetryRequestMsg := helloRetryRequestMsg{
Steven Valdezfdd10992016-09-15 16:27:05 -0400564 vers: versionToWire(c.vers, c.isDTLS),
Nick Harperdcfbc672016-07-16 17:47:31 +0200565 cipherSuite: hs.hello.cipherSuite,
566 selectedGroup: selectedCurve,
567 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400568 if config.Bugs.SendHelloRetryRequestCurve != 0 {
569 helloRetryRequestMsg.selectedGroup = config.Bugs.SendHelloRetryRequestCurve
570 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200571 hs.writeServerHash(helloRetryRequestMsg.marshal())
572 c.writeRecord(recordTypeHandshake, helloRetryRequestMsg.marshal())
David Benjamine73c7f42016-08-17 00:29:33 -0400573 c.flushHandshake()
Nick Harperdcfbc672016-07-16 17:47:31 +0200574
575 // Read new ClientHello.
576 newMsg, err := c.readHandshake()
577 if err != nil {
578 return err
579 }
580 newClientHello, ok := newMsg.(*clientHelloMsg)
581 if !ok {
582 c.sendAlert(alertUnexpectedMessage)
583 return unexpectedMessageError(newClientHello, newMsg)
584 }
585 hs.writeClientHash(newClientHello.marshal())
586
587 // Check that the new ClientHello matches the old ClientHello, except for
588 // the addition of the new KeyShareEntry at the end of the list, and
589 // removing the EarlyDataIndication extension (if present).
590 newKeyShares := newClientHello.keyShares
591 if len(newKeyShares) == 0 || newKeyShares[len(newKeyShares)-1].group != selectedCurve {
592 return errors.New("tls: KeyShare from HelloRetryRequest not present in new ClientHello")
593 }
594 oldClientHelloCopy := *hs.clientHello
595 oldClientHelloCopy.raw = nil
596 oldClientHelloCopy.hasEarlyData = false
597 oldClientHelloCopy.earlyDataContext = nil
598 newClientHelloCopy := *newClientHello
599 newClientHelloCopy.raw = nil
600 newClientHelloCopy.keyShares = newKeyShares[:len(newKeyShares)-1]
601 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
602 return errors.New("tls: new ClientHello does not match")
603 }
604
Steven Valdez5440fe02016-07-18 12:40:30 -0400605 if firstTime && config.Bugs.SecondHelloRetryRequest {
606 firstTime = false
607 goto ResendHelloRetryRequest
608 }
609
Nick Harperdcfbc672016-07-16 17:47:31 +0200610 selectedKeyShare = &newKeyShares[len(newKeyShares)-1]
Nick Harper728eed82016-07-07 17:36:52 -0700611 }
612
613 // Once a curve has been selected and a key share identified,
614 // the server needs to generate a public value and send it in
615 // the ServerHello.
Steven Valdez5440fe02016-07-18 12:40:30 -0400616 curve, ok := curveForCurveID(selectedCurve)
Nick Harper728eed82016-07-07 17:36:52 -0700617 if !ok {
618 panic("tls: server failed to look up curve ID")
619 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400620 c.curveID = selectedCurve
621
622 var peerKey []byte
623 if config.Bugs.SkipHelloRetryRequest {
624 // If skipping HelloRetryRequest, use a random key to
625 // avoid crashing.
626 curve2, _ := curveForCurveID(selectedCurve)
627 var err error
628 peerKey, err = curve2.offer(config.rand())
629 if err != nil {
630 return err
631 }
632 } else {
633 peerKey = selectedKeyShare.keyExchange
634 }
635
Nick Harper728eed82016-07-07 17:36:52 -0700636 var publicKey []byte
637 var err error
Steven Valdez5440fe02016-07-18 12:40:30 -0400638 publicKey, ecdheSecret, err = curve.accept(config.rand(), peerKey)
Nick Harper728eed82016-07-07 17:36:52 -0700639 if err != nil {
640 c.sendAlert(alertHandshakeFailure)
641 return err
642 }
643 hs.hello.hasKeyShare = true
Steven Valdez0ee2e112016-07-15 06:51:15 -0400644
Steven Valdez5440fe02016-07-18 12:40:30 -0400645 curveID := selectedCurve
Steven Valdez0ee2e112016-07-15 06:51:15 -0400646 if c.config.Bugs.SendCurve != 0 {
647 curveID = config.Bugs.SendCurve
648 }
649 if c.config.Bugs.InvalidECDHPoint {
650 publicKey[0] ^= 0xff
651 }
652
Nick Harper728eed82016-07-07 17:36:52 -0700653 hs.hello.keyShare = keyShareEntry{
Steven Valdez0ee2e112016-07-15 06:51:15 -0400654 group: curveID,
Nick Harper728eed82016-07-07 17:36:52 -0700655 keyExchange: publicKey,
656 }
Steven Valdez143e8b32016-07-11 13:19:03 -0400657
658 if config.Bugs.EncryptedExtensionsWithKeyShare {
659 encryptedExtensions.extensions.hasKeyShare = true
660 encryptedExtensions.extensions.keyShare = keyShareEntry{
661 group: curveID,
662 keyExchange: publicKey,
663 }
664 }
Nick Harper728eed82016-07-07 17:36:52 -0700665 } else {
666 ecdheSecret = hs.finishedHash.zeroSecret()
667 }
668
669 // Send unencrypted ServerHello.
670 hs.writeServerHash(hs.hello.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400671 if config.Bugs.PartialEncryptedExtensionsWithServerHello {
672 helloBytes := hs.hello.marshal()
673 toWrite := make([]byte, 0, len(helloBytes)+1)
674 toWrite = append(toWrite, helloBytes...)
675 toWrite = append(toWrite, typeEncryptedExtensions)
676 c.writeRecord(recordTypeHandshake, toWrite)
677 } else {
678 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
679 }
Nick Harper728eed82016-07-07 17:36:52 -0700680 c.flushHandshake()
681
682 // Compute the handshake secret.
683 handshakeSecret := hs.finishedHash.extractKey(earlySecret, ecdheSecret)
684
685 // Switch to handshake traffic keys.
686 handshakeTrafficSecret := hs.finishedHash.deriveSecret(handshakeSecret, handshakeTrafficLabel)
David Benjamin21c00282016-07-18 21:56:23 +0200687 c.out.useTrafficSecret(c.vers, hs.suite, handshakeTrafficSecret, handshakePhase, serverWrite)
688 c.in.useTrafficSecret(c.vers, hs.suite, handshakeTrafficSecret, handshakePhase, clientWrite)
Nick Harper728eed82016-07-07 17:36:52 -0700689
Steven Valdez803c77a2016-09-06 14:13:43 -0400690 if hs.hello.useCertAuth {
David Benjamin615119a2016-07-06 19:22:55 -0700691 if hs.clientHello.ocspStapling {
692 encryptedExtensions.extensions.ocspResponse = hs.cert.OCSPStaple
693 }
694 if hs.clientHello.sctListSupported {
695 encryptedExtensions.extensions.sctList = hs.cert.SignedCertificateTimestampList
696 }
David Benjamindaa88502016-10-04 16:32:16 -0400697 } else {
698 if config.Bugs.SendOCSPResponseOnResume != nil {
699 encryptedExtensions.extensions.ocspResponse = config.Bugs.SendOCSPResponseOnResume
700 }
701 if config.Bugs.SendSCTListOnResume != nil {
702 encryptedExtensions.extensions.sctList = config.Bugs.SendSCTListOnResume
703 }
David Benjamin615119a2016-07-06 19:22:55 -0700704 }
705
Nick Harper728eed82016-07-07 17:36:52 -0700706 // Send EncryptedExtensions.
707 hs.writeServerHash(encryptedExtensions.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400708 if config.Bugs.PartialEncryptedExtensionsWithServerHello {
709 // The first byte has already been sent.
710 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()[1:])
711 } else {
712 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal())
713 }
Nick Harper728eed82016-07-07 17:36:52 -0700714
Steven Valdez803c77a2016-09-06 14:13:43 -0400715 if hs.hello.useCertAuth {
Nick Harper728eed82016-07-07 17:36:52 -0700716 if config.ClientAuth >= RequestClientCert {
David Benjamin8d343b42016-07-09 14:26:01 -0700717 // Request a client certificate
718 certReq := &certificateRequestMsg{
719 hasSignatureAlgorithm: true,
720 hasRequestContext: true,
David Benjamin8a8349b2016-08-18 02:32:23 -0400721 requestContext: config.Bugs.SendRequestContext,
David Benjamin8d343b42016-07-09 14:26:01 -0700722 }
723 if !config.Bugs.NoSignatureAlgorithms {
David Benjaminf74ec792016-07-13 21:18:49 -0400724 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin8d343b42016-07-09 14:26:01 -0700725 }
726
727 // An empty list of certificateAuthorities signals to
728 // the client that it may send any certificate in response
729 // to our request. When we know the CAs we trust, then
730 // we can send them down, so that the client can choose
731 // an appropriate certificate to give to us.
732 if config.ClientCAs != nil {
733 certReq.certificateAuthorities = config.ClientCAs.Subjects()
734 }
735 hs.writeServerHash(certReq.marshal())
736 c.writeRecord(recordTypeHandshake, certReq.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700737 }
738
739 certMsg := &certificateMsg{
740 hasRequestContext: true,
741 }
742 if !config.Bugs.EmptyCertificateList {
743 certMsg.certificates = hs.cert.Certificate
744 }
David Benjamin1edae6b2016-07-13 16:58:23 -0400745 certMsgBytes := certMsg.marshal()
David Benjamin1edae6b2016-07-13 16:58:23 -0400746 hs.writeServerHash(certMsgBytes)
747 c.writeRecord(recordTypeHandshake, certMsgBytes)
Nick Harper728eed82016-07-07 17:36:52 -0700748
749 certVerify := &certificateVerifyMsg{
750 hasSignatureAlgorithm: true,
751 }
752
753 // Determine the hash to sign.
754 privKey := hs.cert.PrivateKey
755
756 var err error
757 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, config, hs.clientHello.signatureAlgorithms)
758 if err != nil {
759 c.sendAlert(alertInternalError)
760 return err
761 }
762
763 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
764 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
765 if err != nil {
766 c.sendAlert(alertInternalError)
767 return err
768 }
769
Steven Valdez0ee2e112016-07-15 06:51:15 -0400770 if config.Bugs.SendSignatureAlgorithm != 0 {
771 certVerify.signatureAlgorithm = config.Bugs.SendSignatureAlgorithm
772 }
773
Nick Harper728eed82016-07-07 17:36:52 -0700774 hs.writeServerHash(certVerify.marshal())
775 c.writeRecord(recordTypeHandshake, certVerify.marshal())
Steven Valdez803c77a2016-09-06 14:13:43 -0400776 } else if hs.sessionState != nil {
Nick Harper0b3625b2016-07-25 16:16:28 -0700777 // Pick up certificates from the session instead.
David Benjamin5ecb88b2016-10-04 17:51:35 -0400778 if len(hs.sessionState.certificates) > 0 {
Nick Harper0b3625b2016-07-25 16:16:28 -0700779 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
780 return err
781 }
782 }
Nick Harper728eed82016-07-07 17:36:52 -0700783 }
784
785 finished := new(finishedMsg)
786 finished.verifyData = hs.finishedHash.serverSum(handshakeTrafficSecret)
787 if config.Bugs.BadFinished {
788 finished.verifyData[0]++
789 }
790 hs.writeServerHash(finished.marshal())
791 c.writeRecord(recordTypeHandshake, finished.marshal())
David Benjamin02edcd02016-07-27 17:40:37 -0400792 if c.config.Bugs.SendExtraFinished {
793 c.writeRecord(recordTypeHandshake, finished.marshal())
794 }
Nick Harper728eed82016-07-07 17:36:52 -0700795 c.flushHandshake()
796
797 // The various secrets do not incorporate the client's final leg, so
798 // derive them now before updating the handshake context.
799 masterSecret := hs.finishedHash.extractKey(handshakeSecret, hs.finishedHash.zeroSecret())
800 trafficSecret := hs.finishedHash.deriveSecret(masterSecret, applicationTrafficLabel)
801
David Benjamin2aad4062016-07-14 23:15:40 -0400802 // Switch to application data keys on write. In particular, any alerts
803 // from the client certificate are sent over these keys.
David Benjamin21c00282016-07-18 21:56:23 +0200804 c.out.useTrafficSecret(c.vers, hs.suite, trafficSecret, applicationPhase, serverWrite)
David Benjamin2aad4062016-07-14 23:15:40 -0400805
Nick Harper728eed82016-07-07 17:36:52 -0700806 // If we requested a client certificate, then the client must send a
807 // certificate message, even if it's empty.
808 if config.ClientAuth >= RequestClientCert {
David Benjamin8d343b42016-07-09 14:26:01 -0700809 msg, err := c.readHandshake()
810 if err != nil {
811 return err
812 }
813
814 certMsg, ok := msg.(*certificateMsg)
815 if !ok {
816 c.sendAlert(alertUnexpectedMessage)
817 return unexpectedMessageError(certMsg, msg)
818 }
819 hs.writeClientHash(certMsg.marshal())
820
821 if len(certMsg.certificates) == 0 {
822 // The client didn't actually send a certificate
823 switch config.ClientAuth {
824 case RequireAnyClientCert, RequireAndVerifyClientCert:
825 c.sendAlert(alertBadCertificate)
826 return errors.New("tls: client didn't provide a certificate")
827 }
828 }
829
830 pub, err := hs.processCertsFromClient(certMsg.certificates)
831 if err != nil {
832 return err
833 }
834
835 if len(c.peerCertificates) > 0 {
836 msg, err = c.readHandshake()
837 if err != nil {
838 return err
839 }
840
841 certVerify, ok := msg.(*certificateVerifyMsg)
842 if !ok {
843 c.sendAlert(alertUnexpectedMessage)
844 return unexpectedMessageError(certVerify, msg)
845 }
846
David Benjaminf74ec792016-07-13 21:18:49 -0400847 c.peerSignatureAlgorithm = certVerify.signatureAlgorithm
David Benjamin8d343b42016-07-09 14:26:01 -0700848 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
849 if err := verifyMessage(c.vers, pub, config, certVerify.signatureAlgorithm, input, certVerify.signature); err != nil {
850 c.sendAlert(alertBadCertificate)
851 return err
852 }
853 hs.writeClientHash(certVerify.marshal())
854 }
Nick Harper728eed82016-07-07 17:36:52 -0700855 }
856
857 // Read the client Finished message.
858 msg, err := c.readHandshake()
859 if err != nil {
860 return err
861 }
862 clientFinished, ok := msg.(*finishedMsg)
863 if !ok {
864 c.sendAlert(alertUnexpectedMessage)
865 return unexpectedMessageError(clientFinished, msg)
866 }
867
868 verify := hs.finishedHash.clientSum(handshakeTrafficSecret)
869 if len(verify) != len(clientFinished.verifyData) ||
870 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
871 c.sendAlert(alertHandshakeFailure)
872 return errors.New("tls: client's Finished message was incorrect")
873 }
David Benjamin97a0a082016-07-13 17:57:35 -0400874 hs.writeClientHash(clientFinished.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700875
David Benjamin2aad4062016-07-14 23:15:40 -0400876 // Switch to application data keys on read.
David Benjamin21c00282016-07-18 21:56:23 +0200877 c.in.useTrafficSecret(c.vers, hs.suite, trafficSecret, applicationPhase, clientWrite)
Nick Harper728eed82016-07-07 17:36:52 -0700878
Nick Harper728eed82016-07-07 17:36:52 -0700879 c.cipherSuite = hs.suite
David Benjamin97a0a082016-07-13 17:57:35 -0400880 c.exporterSecret = hs.finishedHash.deriveSecret(masterSecret, exporterLabel)
David Benjamin58104882016-07-18 01:25:41 +0200881 c.resumptionSecret = hs.finishedHash.deriveSecret(masterSecret, resumptionLabel)
882
883 // TODO(davidben): Allow configuring the number of tickets sent for
884 // testing.
885 if !c.config.SessionTicketsDisabled {
886 ticketCount := 2
887 for i := 0; i < ticketCount; i++ {
888 c.SendNewSessionTicket()
889 }
890 }
Nick Harper728eed82016-07-07 17:36:52 -0700891 return nil
892}
893
David Benjaminf25dda92016-07-04 10:05:26 -0700894// processClientHello processes the ClientHello message from the client and
895// decides whether we will perform session resumption.
896func (hs *serverHandshakeState) processClientHello() (isResume bool, err error) {
897 config := hs.c.config
898 c := hs.c
899
900 hs.hello = &serverHelloMsg{
901 isDTLS: c.isDTLS,
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400902 vers: versionToWire(c.vers, c.isDTLS),
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400903 versOverride: config.Bugs.SendServerHelloVersion,
David Benjaminf25dda92016-07-04 10:05:26 -0700904 compressionMethod: compressionNone,
905 }
906
907 hs.hello.random = make([]byte, 32)
908 _, err = io.ReadFull(config.rand(), hs.hello.random)
909 if err != nil {
910 c.sendAlert(alertInternalError)
911 return false, err
912 }
David Benjamin1f61f0d2016-07-10 12:20:35 -0400913 // Signal downgrades in the server random, per draft-ietf-tls-tls13-14,
914 // section 6.3.1.2.
Nick Harper85f20c22016-07-04 10:11:59 -0700915 if c.vers <= VersionTLS12 && config.maxVersion(c.isDTLS) >= VersionTLS13 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400916 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS13)
Nick Harper85f20c22016-07-04 10:11:59 -0700917 }
918 if c.vers <= VersionTLS11 && config.maxVersion(c.isDTLS) == VersionTLS12 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400919 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS12)
Nick Harper85f20c22016-07-04 10:11:59 -0700920 }
David Benjaminf25dda92016-07-04 10:05:26 -0700921
922 foundCompression := false
923 // We only support null compression, so check that the client offered it.
924 for _, compression := range hs.clientHello.compressionMethods {
925 if compression == compressionNone {
926 foundCompression = true
927 break
928 }
929 }
930
931 if !foundCompression {
932 c.sendAlert(alertHandshakeFailure)
933 return false, errors.New("tls: client does not support uncompressed connections")
934 }
David Benjamin7d79f832016-07-04 09:20:45 -0700935
936 if err := hs.processClientExtensions(&hs.hello.extensions); err != nil {
937 return false, err
Adam Langley09505632015-07-30 18:10:13 -0700938 }
Adam Langley95c29f32014-06-20 12:00:00 -0700939
940 supportedCurve := false
941 preferredCurves := config.curvePreferences()
942Curves:
943 for _, curve := range hs.clientHello.supportedCurves {
944 for _, supported := range preferredCurves {
945 if supported == curve {
946 supportedCurve = true
947 break Curves
948 }
949 }
950 }
951
952 supportedPointFormat := false
953 for _, pointFormat := range hs.clientHello.supportedPoints {
954 if pointFormat == pointFormatUncompressed {
955 supportedPointFormat = true
956 break
957 }
958 }
959 hs.ellipticOk = supportedCurve && supportedPointFormat
960
Adam Langley95c29f32014-06-20 12:00:00 -0700961 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
962
David Benjamin4b27d9f2015-05-12 22:42:52 -0400963 // For test purposes, check that the peer never offers a session when
964 // renegotiating.
965 if c.cipherSuite != nil && len(hs.clientHello.sessionId) > 0 && c.config.Bugs.FailIfResumeOnRenego {
966 return false, errors.New("tls: offered resumption on renegotiation")
967 }
968
David Benjamindd6fed92015-10-23 17:41:12 -0400969 if c.config.Bugs.FailIfSessionOffered && (len(hs.clientHello.sessionTicket) > 0 || len(hs.clientHello.sessionId) > 0) {
970 return false, errors.New("tls: client offered a session ticket or ID")
971 }
972
Adam Langley95c29f32014-06-20 12:00:00 -0700973 if hs.checkForResumption() {
974 return true, nil
975 }
976
Adam Langley95c29f32014-06-20 12:00:00 -0700977 var preferenceList, supportedList []uint16
978 if c.config.PreferServerCipherSuites {
979 preferenceList = c.config.cipherSuites()
980 supportedList = hs.clientHello.cipherSuites
981 } else {
982 preferenceList = hs.clientHello.cipherSuites
983 supportedList = c.config.cipherSuites()
984 }
985
986 for _, id := range preferenceList {
Steven Valdez803c77a2016-09-06 14:13:43 -0400987 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700988 break
989 }
990 }
991
992 if hs.suite == nil {
993 c.sendAlert(alertHandshakeFailure)
994 return false, errors.New("tls: no cipher suite supported by both client and server")
995 }
996
997 return false, nil
998}
999
David Benjamin7d79f832016-07-04 09:20:45 -07001000// processClientExtensions processes all ClientHello extensions not directly
1001// related to cipher suite negotiation and writes responses in serverExtensions.
1002func (hs *serverHandshakeState) processClientExtensions(serverExtensions *serverExtensions) error {
1003 config := hs.c.config
1004 c := hs.c
1005
David Benjamin8d315d72016-07-18 01:03:18 +02001006 if c.vers < VersionTLS13 || config.Bugs.NegotiateRenegotiationInfoAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -07001007 if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) {
1008 c.sendAlert(alertHandshakeFailure)
1009 return errors.New("tls: renegotiation mismatch")
David Benjamin7d79f832016-07-04 09:20:45 -07001010 }
David Benjamin7d79f832016-07-04 09:20:45 -07001011
Nick Harper728eed82016-07-07 17:36:52 -07001012 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
1013 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.clientVerify...)
1014 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.serverVerify...)
1015 if c.config.Bugs.BadRenegotiationInfo {
1016 serverExtensions.secureRenegotiation[0] ^= 0x80
1017 }
1018 } else {
1019 serverExtensions.secureRenegotiation = hs.clientHello.secureRenegotiation
1020 }
1021
1022 if c.noRenegotiationInfo() {
1023 serverExtensions.secureRenegotiation = nil
1024 }
David Benjamin7d79f832016-07-04 09:20:45 -07001025 }
1026
1027 serverExtensions.duplicateExtension = c.config.Bugs.DuplicateExtension
1028
1029 if len(hs.clientHello.serverName) > 0 {
1030 c.serverName = hs.clientHello.serverName
1031 }
1032 if len(config.Certificates) == 0 {
1033 c.sendAlert(alertInternalError)
1034 return errors.New("tls: no certificates configured")
1035 }
1036 hs.cert = &config.Certificates[0]
1037 if len(hs.clientHello.serverName) > 0 {
1038 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
1039 }
1040 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
1041 return errors.New("tls: unexpected server name")
1042 }
1043
1044 if len(hs.clientHello.alpnProtocols) > 0 {
1045 if proto := c.config.Bugs.ALPNProtocol; proto != nil {
1046 serverExtensions.alpnProtocol = *proto
1047 serverExtensions.alpnProtocolEmpty = len(*proto) == 0
1048 c.clientProtocol = *proto
1049 c.usedALPN = true
1050 } else if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
1051 serverExtensions.alpnProtocol = selectedProto
1052 c.clientProtocol = selectedProto
1053 c.usedALPN = true
1054 }
1055 }
Nick Harper728eed82016-07-07 17:36:52 -07001056
David Benjamin0c40a962016-08-01 12:05:50 -04001057 if len(c.config.Bugs.SendALPN) > 0 {
1058 serverExtensions.alpnProtocol = c.config.Bugs.SendALPN
1059 }
1060
David Benjamin8d315d72016-07-18 01:03:18 +02001061 if c.vers < VersionTLS13 || config.Bugs.NegotiateNPNAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -07001062 if len(hs.clientHello.alpnProtocols) == 0 || c.config.Bugs.NegotiateALPNAndNPN {
1063 // Although sending an empty NPN extension is reasonable, Firefox has
1064 // had a bug around this. Best to send nothing at all if
1065 // config.NextProtos is empty. See
1066 // https://code.google.com/p/go/issues/detail?id=5445.
1067 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
1068 serverExtensions.nextProtoNeg = true
1069 serverExtensions.nextProtos = config.NextProtos
1070 serverExtensions.npnLast = config.Bugs.SwapNPNAndALPN
1071 }
David Benjamin7d79f832016-07-04 09:20:45 -07001072 }
Steven Valdez143e8b32016-07-11 13:19:03 -04001073 }
David Benjamin7d79f832016-07-04 09:20:45 -07001074
David Benjamin8d315d72016-07-18 01:03:18 +02001075 if c.vers < VersionTLS13 || config.Bugs.NegotiateEMSAtAllVersions {
David Benjamin163c9562016-08-29 23:14:17 -04001076 disableEMS := config.Bugs.NoExtendedMasterSecret
1077 if c.cipherSuite != nil {
1078 disableEMS = config.Bugs.NoExtendedMasterSecretOnRenegotiation
1079 }
1080 serverExtensions.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !disableEMS
Steven Valdez143e8b32016-07-11 13:19:03 -04001081 }
David Benjamin7d79f832016-07-04 09:20:45 -07001082
David Benjamin8d315d72016-07-18 01:03:18 +02001083 if c.vers < VersionTLS13 || config.Bugs.NegotiateChannelIDAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -07001084 if hs.clientHello.channelIDSupported && config.RequestChannelID {
1085 serverExtensions.channelIDRequested = true
1086 }
David Benjamin7d79f832016-07-04 09:20:45 -07001087 }
1088
1089 if hs.clientHello.srtpProtectionProfiles != nil {
1090 SRTPLoop:
1091 for _, p1 := range c.config.SRTPProtectionProfiles {
1092 for _, p2 := range hs.clientHello.srtpProtectionProfiles {
1093 if p1 == p2 {
1094 serverExtensions.srtpProtectionProfile = p1
1095 c.srtpProtectionProfile = p1
1096 break SRTPLoop
1097 }
1098 }
1099 }
1100 }
1101
1102 if c.config.Bugs.SendSRTPProtectionProfile != 0 {
1103 serverExtensions.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
1104 }
1105
1106 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
1107 if hs.clientHello.customExtension != *expected {
1108 return fmt.Errorf("tls: bad custom extension contents %q", hs.clientHello.customExtension)
1109 }
1110 }
1111 serverExtensions.customExtension = config.Bugs.CustomExtension
1112
Steven Valdez143e8b32016-07-11 13:19:03 -04001113 if c.config.Bugs.AdvertiseTicketExtension {
1114 serverExtensions.ticketSupported = true
1115 }
1116
David Benjamin65ac9972016-09-02 21:35:25 -04001117 if !hs.clientHello.hasGREASEExtension && config.Bugs.ExpectGREASE {
1118 return errors.New("tls: no GREASE extension found")
1119 }
1120
David Benjamin7d79f832016-07-04 09:20:45 -07001121 return nil
1122}
1123
Adam Langley95c29f32014-06-20 12:00:00 -07001124// checkForResumption returns true if we should perform resumption on this connection.
1125func (hs *serverHandshakeState) checkForResumption() bool {
1126 c := hs.c
1127
David Benjamin405da482016-08-08 17:25:07 -04001128 ticket := hs.clientHello.sessionTicket
1129 if len(ticket) == 0 && len(hs.clientHello.pskIdentities) > 0 && c.config.Bugs.AcceptAnySession {
Steven Valdez5b986082016-09-01 12:29:49 -04001130 ticket = hs.clientHello.pskIdentities[0].ticket
David Benjamin405da482016-08-08 17:25:07 -04001131 }
1132 if len(ticket) > 0 {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001133 if c.config.SessionTicketsDisabled {
1134 return false
1135 }
David Benjaminb0c8db72014-09-24 15:19:56 -04001136
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001137 var ok bool
David Benjamin405da482016-08-08 17:25:07 -04001138 if hs.sessionState, ok = c.decryptTicket(ticket); !ok {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001139 return false
1140 }
1141 } else {
1142 if c.config.ServerSessionCache == nil {
1143 return false
1144 }
1145
1146 var ok bool
1147 sessionId := string(hs.clientHello.sessionId)
1148 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
1149 return false
1150 }
Adam Langley95c29f32014-06-20 12:00:00 -07001151 }
1152
Steven Valdez803c77a2016-09-06 14:13:43 -04001153 if c.config.Bugs.AcceptAnySession {
1154 // Replace the cipher suite with one known to work, to test
1155 // cross-version resumption attempts.
1156 hs.sessionState.cipherSuite = TLS_RSA_WITH_AES_128_CBC_SHA
1157 } else {
David Benjamin405da482016-08-08 17:25:07 -04001158 // Never resume a session for a different SSL version.
1159 if c.vers != hs.sessionState.vers {
1160 return false
Adam Langley95c29f32014-06-20 12:00:00 -07001161 }
David Benjamin405da482016-08-08 17:25:07 -04001162
1163 cipherSuiteOk := false
1164 // Check that the client is still offering the ciphersuite in the session.
1165 for _, id := range hs.clientHello.cipherSuites {
1166 if id == hs.sessionState.cipherSuite {
1167 cipherSuiteOk = true
1168 break
1169 }
1170 }
1171 if !cipherSuiteOk {
1172 return false
1173 }
Adam Langley95c29f32014-06-20 12:00:00 -07001174 }
1175
1176 // Check that we also support the ciphersuite from the session.
Steven Valdez803c77a2016-09-06 14:13:43 -04001177 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), c.vers, hs.ellipticOk, hs.ecdsaOk)
1178
Adam Langley95c29f32014-06-20 12:00:00 -07001179 if hs.suite == nil {
1180 return false
1181 }
1182
1183 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
1184 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
1185 if needClientCerts && !sessionHasClientCerts {
1186 return false
1187 }
1188 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
1189 return false
1190 }
1191
1192 return true
1193}
1194
1195func (hs *serverHandshakeState) doResumeHandshake() error {
1196 c := hs.c
1197
1198 hs.hello.cipherSuite = hs.suite.id
David Benjaminece3de92015-03-16 18:02:20 -04001199 if c.config.Bugs.SendCipherSuite != 0 {
1200 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
1201 }
Adam Langley95c29f32014-06-20 12:00:00 -07001202 // We echo the client's session ID in the ServerHello to let it know
1203 // that we're doing a resumption.
1204 hs.hello.sessionId = hs.clientHello.sessionId
Nick Harperb3d51be2016-07-01 11:43:18 -04001205 hs.hello.extensions.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -07001206
David Benjamin80d1b352016-05-04 19:19:06 -04001207 if c.config.Bugs.SendSCTListOnResume != nil {
Nick Harperb3d51be2016-07-01 11:43:18 -04001208 hs.hello.extensions.sctList = c.config.Bugs.SendSCTListOnResume
David Benjamin80d1b352016-05-04 19:19:06 -04001209 }
1210
David Benjamindaa88502016-10-04 16:32:16 -04001211 if c.config.Bugs.SendOCSPResponseOnResume != nil {
1212 // There is no way, syntactically, to send an OCSP response on a
1213 // resumption handshake.
1214 hs.hello.extensions.ocspStapling = true
1215 }
1216
Adam Langley95c29f32014-06-20 12:00:00 -07001217 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -04001218 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -04001219 hs.writeClientHash(hs.clientHello.marshal())
1220 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001221
1222 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
1223
1224 if len(hs.sessionState.certificates) > 0 {
1225 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
1226 return err
1227 }
1228 }
1229
1230 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -07001231 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -07001232
1233 return nil
1234}
1235
1236func (hs *serverHandshakeState) doFullHandshake() error {
1237 config := hs.c.config
1238 c := hs.c
1239
David Benjamin48cae082014-10-27 01:06:24 -04001240 isPSK := hs.suite.flags&suitePSK != 0
1241 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001242 hs.hello.extensions.ocspStapling = true
Adam Langley95c29f32014-06-20 12:00:00 -07001243 }
1244
David Benjamin61f95272014-11-25 01:55:35 -05001245 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001246 hs.hello.extensions.sctList = hs.cert.SignedCertificateTimestampList
David Benjamin61f95272014-11-25 01:55:35 -05001247 }
1248
Nick Harperb3d51be2016-07-01 11:43:18 -04001249 hs.hello.extensions.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
Adam Langley95c29f32014-06-20 12:00:00 -07001250 hs.hello.cipherSuite = hs.suite.id
David Benjamin6095de82014-12-27 01:50:38 -05001251 if config.Bugs.SendCipherSuite != 0 {
1252 hs.hello.cipherSuite = config.Bugs.SendCipherSuite
1253 }
Nick Harperb3d51be2016-07-01 11:43:18 -04001254 c.extendedMasterSecret = hs.hello.extensions.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -07001255
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001256 // Generate a session ID if we're to save the session.
Nick Harperb3d51be2016-07-01 11:43:18 -04001257 if !hs.hello.extensions.ticketSupported && config.ServerSessionCache != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001258 hs.hello.sessionId = make([]byte, 32)
1259 if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
1260 c.sendAlert(alertInternalError)
1261 return errors.New("tls: short read from Rand: " + err.Error())
1262 }
1263 }
1264
Adam Langley95c29f32014-06-20 12:00:00 -07001265 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -04001266 hs.writeClientHash(hs.clientHello.marshal())
1267 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001268
David Benjaminabe94e32016-09-04 14:18:58 -04001269 if config.Bugs.SendSNIWarningAlert {
1270 c.SendAlert(alertLevelWarning, alertUnrecognizedName)
1271 }
1272
Adam Langley95c29f32014-06-20 12:00:00 -07001273 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
1274
David Benjamin48cae082014-10-27 01:06:24 -04001275 if !isPSK {
1276 certMsg := new(certificateMsg)
David Benjamin8923c0b2015-06-07 11:42:34 -04001277 if !config.Bugs.EmptyCertificateList {
1278 certMsg.certificates = hs.cert.Certificate
1279 }
David Benjamin48cae082014-10-27 01:06:24 -04001280 if !config.Bugs.UnauthenticatedECDH {
David Benjaminbcb2d912015-02-24 23:45:43 -05001281 certMsgBytes := certMsg.marshal()
David Benjaminbcb2d912015-02-24 23:45:43 -05001282 hs.writeServerHash(certMsgBytes)
1283 c.writeRecord(recordTypeHandshake, certMsgBytes)
David Benjamin48cae082014-10-27 01:06:24 -04001284 }
David Benjamin1c375dd2014-07-12 00:48:23 -04001285 }
Adam Langley95c29f32014-06-20 12:00:00 -07001286
Nick Harperb3d51be2016-07-01 11:43:18 -04001287 if hs.hello.extensions.ocspStapling && !c.config.Bugs.SkipCertificateStatus {
Adam Langley95c29f32014-06-20 12:00:00 -07001288 certStatus := new(certificateStatusMsg)
1289 certStatus.statusType = statusTypeOCSP
1290 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -04001291 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001292 c.writeRecord(recordTypeHandshake, certStatus.marshal())
1293 }
1294
1295 keyAgreement := hs.suite.ka(c.vers)
1296 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
1297 if err != nil {
1298 c.sendAlert(alertHandshakeFailure)
1299 return err
1300 }
Steven Valdez5440fe02016-07-18 12:40:30 -04001301 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
1302 c.curveID = ecdhe.curveID
1303 }
David Benjamin9c651c92014-07-12 13:27:45 -04001304 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -04001305 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001306 c.writeRecord(recordTypeHandshake, skx.marshal())
1307 }
1308
1309 if config.ClientAuth >= RequestClientCert {
1310 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -04001311 certReq := &certificateRequestMsg{
1312 certificateTypes: config.ClientCertificateTypes,
1313 }
1314 if certReq.certificateTypes == nil {
1315 certReq.certificateTypes = []byte{
1316 byte(CertTypeRSASign),
1317 byte(CertTypeECDSASign),
1318 }
Adam Langley95c29f32014-06-20 12:00:00 -07001319 }
1320 if c.vers >= VersionTLS12 {
Nick Harper60edffd2016-06-21 15:19:24 -07001321 certReq.hasSignatureAlgorithm = true
1322 if !config.Bugs.NoSignatureAlgorithms {
David Benjamin7a41d372016-07-09 11:21:54 -07001323 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin000800a2014-11-14 01:43:59 -05001324 }
Adam Langley95c29f32014-06-20 12:00:00 -07001325 }
1326
1327 // An empty list of certificateAuthorities signals to
1328 // the client that it may send any certificate in response
1329 // to our request. When we know the CAs we trust, then
1330 // we can send them down, so that the client can choose
1331 // an appropriate certificate to give to us.
1332 if config.ClientCAs != nil {
1333 certReq.certificateAuthorities = config.ClientCAs.Subjects()
1334 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001335 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001336 c.writeRecord(recordTypeHandshake, certReq.marshal())
1337 }
1338
1339 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001340 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001341 c.writeRecord(recordTypeHandshake, helloDone.marshal())
David Benjamin582ba042016-07-07 12:33:25 -07001342 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001343
1344 var pub crypto.PublicKey // public key for client auth, if any
1345
David Benjamin83f90402015-01-27 01:09:43 -05001346 if err := c.simulatePacketLoss(nil); err != nil {
1347 return err
1348 }
Adam Langley95c29f32014-06-20 12:00:00 -07001349 msg, err := c.readHandshake()
1350 if err != nil {
1351 return err
1352 }
1353
1354 var ok bool
1355 // If we requested a client certificate, then the client must send a
1356 // certificate message, even if it's empty.
1357 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -04001358 var certMsg *certificateMsg
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001359 var certificates [][]byte
1360 if certMsg, ok = msg.(*certificateMsg); ok {
1361 if c.vers == VersionSSL30 && len(certMsg.certificates) == 0 {
1362 return errors.New("tls: empty certificate message in SSL 3.0")
1363 }
1364
1365 hs.writeClientHash(certMsg.marshal())
1366 certificates = certMsg.certificates
1367 } else if c.vers != VersionSSL30 {
1368 // In TLS, the Certificate message is required. In SSL
1369 // 3.0, the peer skips it when sending no certificates.
Adam Langley95c29f32014-06-20 12:00:00 -07001370 c.sendAlert(alertUnexpectedMessage)
1371 return unexpectedMessageError(certMsg, msg)
1372 }
Adam Langley95c29f32014-06-20 12:00:00 -07001373
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001374 if len(certificates) == 0 {
Adam Langley95c29f32014-06-20 12:00:00 -07001375 // The client didn't actually send a certificate
1376 switch config.ClientAuth {
1377 case RequireAnyClientCert, RequireAndVerifyClientCert:
1378 c.sendAlert(alertBadCertificate)
1379 return errors.New("tls: client didn't provide a certificate")
1380 }
1381 }
1382
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001383 pub, err = hs.processCertsFromClient(certificates)
Adam Langley95c29f32014-06-20 12:00:00 -07001384 if err != nil {
1385 return err
1386 }
1387
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001388 if ok {
1389 msg, err = c.readHandshake()
1390 if err != nil {
1391 return err
1392 }
Adam Langley95c29f32014-06-20 12:00:00 -07001393 }
1394 }
1395
1396 // Get client key exchange
1397 ckx, ok := msg.(*clientKeyExchangeMsg)
1398 if !ok {
1399 c.sendAlert(alertUnexpectedMessage)
1400 return unexpectedMessageError(ckx, msg)
1401 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001402 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001403
David Benjamine098ec22014-08-27 23:13:20 -04001404 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
1405 if err != nil {
1406 c.sendAlert(alertHandshakeFailure)
1407 return err
1408 }
Adam Langley75712922014-10-10 16:23:43 -07001409 if c.extendedMasterSecret {
1410 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1411 } else {
1412 if c.config.Bugs.RequireExtendedMasterSecret {
1413 return errors.New("tls: extended master secret required but not supported by peer")
1414 }
1415 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
1416 }
David Benjamine098ec22014-08-27 23:13:20 -04001417
Adam Langley95c29f32014-06-20 12:00:00 -07001418 // If we received a client cert in response to our certificate request message,
1419 // the client will send us a certificateVerifyMsg immediately after the
1420 // clientKeyExchangeMsg. This message is a digest of all preceding
1421 // handshake-layer messages that is signed using the private key corresponding
1422 // to the client's certificate. This allows us to verify that the client is in
1423 // possession of the private key of the certificate.
1424 if len(c.peerCertificates) > 0 {
1425 msg, err = c.readHandshake()
1426 if err != nil {
1427 return err
1428 }
1429 certVerify, ok := msg.(*certificateVerifyMsg)
1430 if !ok {
1431 c.sendAlert(alertUnexpectedMessage)
1432 return unexpectedMessageError(certVerify, msg)
1433 }
1434
David Benjaminde620d92014-07-18 15:03:41 -04001435 // Determine the signature type.
Nick Harper60edffd2016-06-21 15:19:24 -07001436 var sigAlg signatureAlgorithm
1437 if certVerify.hasSignatureAlgorithm {
1438 sigAlg = certVerify.signatureAlgorithm
Nick Harper60edffd2016-06-21 15:19:24 -07001439 c.peerSignatureAlgorithm = sigAlg
David Benjaminde620d92014-07-18 15:03:41 -04001440 }
1441
Nick Harper60edffd2016-06-21 15:19:24 -07001442 if c.vers > VersionSSL30 {
David Benjamin1fb125c2016-07-08 18:52:12 -07001443 err = verifyMessage(c.vers, pub, c.config, sigAlg, hs.finishedHash.buffer, certVerify.signature)
Nick Harper60edffd2016-06-21 15:19:24 -07001444 } else {
1445 // SSL 3.0's client certificate construction is
1446 // incompatible with signatureAlgorithm.
1447 rsaPub, ok := pub.(*rsa.PublicKey)
1448 if !ok {
1449 err = errors.New("unsupported key type for client certificate")
1450 } else {
1451 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
1452 err = rsa.VerifyPKCS1v15(rsaPub, crypto.MD5SHA1, digest, certVerify.signature)
David Benjaminde620d92014-07-18 15:03:41 -04001453 }
Adam Langley95c29f32014-06-20 12:00:00 -07001454 }
1455 if err != nil {
1456 c.sendAlert(alertBadCertificate)
1457 return errors.New("could not validate signature of connection nonces: " + err.Error())
1458 }
1459
David Benjamin83c0bc92014-08-04 01:23:53 -04001460 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001461 }
1462
David Benjamine098ec22014-08-27 23:13:20 -04001463 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001464
1465 return nil
1466}
1467
1468func (hs *serverHandshakeState) establishKeys() error {
1469 c := hs.c
1470
1471 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001472 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 -07001473
1474 var clientCipher, serverCipher interface{}
1475 var clientHash, serverHash macFunction
1476
1477 if hs.suite.aead == nil {
1478 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
1479 clientHash = hs.suite.mac(c.vers, clientMAC)
1480 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
1481 serverHash = hs.suite.mac(c.vers, serverMAC)
1482 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001483 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1484 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001485 }
1486
1487 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
1488 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
1489
1490 return nil
1491}
1492
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001493func (hs *serverHandshakeState) readFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001494 c := hs.c
1495
1496 c.readRecord(recordTypeChangeCipherSpec)
1497 if err := c.in.error(); err != nil {
1498 return err
1499 }
1500
Nick Harperb3d51be2016-07-01 11:43:18 -04001501 if hs.hello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001502 msg, err := c.readHandshake()
1503 if err != nil {
1504 return err
1505 }
1506 nextProto, ok := msg.(*nextProtoMsg)
1507 if !ok {
1508 c.sendAlert(alertUnexpectedMessage)
1509 return unexpectedMessageError(nextProto, msg)
1510 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001511 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001512 c.clientProtocol = nextProto.proto
1513 }
1514
Nick Harperb3d51be2016-07-01 11:43:18 -04001515 if hs.hello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001516 msg, err := c.readHandshake()
1517 if err != nil {
1518 return err
1519 }
David Benjamin24599a82016-06-30 18:56:53 -04001520 channelIDMsg, ok := msg.(*channelIDMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001521 if !ok {
1522 c.sendAlert(alertUnexpectedMessage)
David Benjamin24599a82016-06-30 18:56:53 -04001523 return unexpectedMessageError(channelIDMsg, msg)
David Benjamind30a9902014-08-24 01:44:23 -04001524 }
David Benjamin24599a82016-06-30 18:56:53 -04001525 x := new(big.Int).SetBytes(channelIDMsg.channelID[0:32])
1526 y := new(big.Int).SetBytes(channelIDMsg.channelID[32:64])
1527 r := new(big.Int).SetBytes(channelIDMsg.channelID[64:96])
1528 s := new(big.Int).SetBytes(channelIDMsg.channelID[96:128])
David Benjamind30a9902014-08-24 01:44:23 -04001529 if !elliptic.P256().IsOnCurve(x, y) {
1530 return errors.New("tls: invalid channel ID public key")
1531 }
1532 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
1533 var resumeHash []byte
1534 if isResume {
1535 resumeHash = hs.sessionState.handshakeHash
1536 }
1537 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
1538 return errors.New("tls: invalid channel ID signature")
1539 }
1540 c.channelID = channelID
1541
David Benjamin24599a82016-06-30 18:56:53 -04001542 hs.writeClientHash(channelIDMsg.marshal())
David Benjamind30a9902014-08-24 01:44:23 -04001543 }
1544
Adam Langley95c29f32014-06-20 12:00:00 -07001545 msg, err := c.readHandshake()
1546 if err != nil {
1547 return err
1548 }
1549 clientFinished, ok := msg.(*finishedMsg)
1550 if !ok {
1551 c.sendAlert(alertUnexpectedMessage)
1552 return unexpectedMessageError(clientFinished, msg)
1553 }
1554
1555 verify := hs.finishedHash.clientSum(hs.masterSecret)
1556 if len(verify) != len(clientFinished.verifyData) ||
1557 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
1558 c.sendAlert(alertHandshakeFailure)
1559 return errors.New("tls: client's Finished message is incorrect")
1560 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001561 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001562 copy(out, clientFinished.verifyData)
Adam Langley95c29f32014-06-20 12:00:00 -07001563
David Benjamin83c0bc92014-08-04 01:23:53 -04001564 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001565 return nil
1566}
1567
1568func (hs *serverHandshakeState) sendSessionTicket() error {
Adam Langley95c29f32014-06-20 12:00:00 -07001569 c := hs.c
Adam Langley95c29f32014-06-20 12:00:00 -07001570 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -04001571 vers: c.vers,
1572 cipherSuite: hs.suite.id,
1573 masterSecret: hs.masterSecret,
1574 certificates: hs.certsFromClient,
1575 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -07001576 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001577
Nick Harperb3d51be2016-07-01 11:43:18 -04001578 if !hs.hello.extensions.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001579 if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
1580 c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
1581 }
1582 return nil
1583 }
1584
1585 m := new(newSessionTicketMsg)
1586
David Benjamindd6fed92015-10-23 17:41:12 -04001587 if !c.config.Bugs.SendEmptySessionTicket {
1588 var err error
1589 m.ticket, err = c.encryptTicket(&state)
1590 if err != nil {
1591 return err
1592 }
Adam Langley95c29f32014-06-20 12:00:00 -07001593 }
Adam Langley95c29f32014-06-20 12:00:00 -07001594
David Benjamin83c0bc92014-08-04 01:23:53 -04001595 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001596 c.writeRecord(recordTypeHandshake, m.marshal())
1597
1598 return nil
1599}
1600
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001601func (hs *serverHandshakeState) sendFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001602 c := hs.c
1603
David Benjamin86271ee2014-07-21 16:14:03 -04001604 finished := new(finishedMsg)
1605 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001606 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001607 if c.config.Bugs.BadFinished {
1608 finished.verifyData[0]++
1609 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001610 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001611 hs.finishedBytes = finished.marshal()
1612 hs.writeServerHash(hs.finishedBytes)
1613 postCCSBytes := hs.finishedBytes
David Benjamin86271ee2014-07-21 16:14:03 -04001614
1615 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
1616 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
1617 postCCSBytes = postCCSBytes[5:]
David Benjamin61672812016-07-14 23:10:43 -04001618 } else if c.config.Bugs.SendUnencryptedFinished {
1619 c.writeRecord(recordTypeHandshake, postCCSBytes)
1620 postCCSBytes = nil
David Benjamin86271ee2014-07-21 16:14:03 -04001621 }
David Benjamin582ba042016-07-07 12:33:25 -07001622 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001623
David Benjamina0e52232014-07-19 17:39:58 -04001624 if !c.config.Bugs.SkipChangeCipherSpec {
David Benjamin8411b242015-11-26 12:07:28 -05001625 ccs := []byte{1}
1626 if c.config.Bugs.BadChangeCipherSpec != nil {
1627 ccs = c.config.Bugs.BadChangeCipherSpec
1628 }
1629 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamina0e52232014-07-19 17:39:58 -04001630 }
Adam Langley95c29f32014-06-20 12:00:00 -07001631
David Benjamin4189bd92015-01-25 23:52:39 -05001632 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1633 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1634 }
David Benjamindc3da932015-03-12 15:09:02 -04001635 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1636 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1637 return errors.New("tls: simulating post-CCS alert")
1638 }
David Benjamin4189bd92015-01-25 23:52:39 -05001639
David Benjamin61672812016-07-14 23:10:43 -04001640 if !c.config.Bugs.SkipFinished && len(postCCSBytes) > 0 {
David Benjaminb80168e2015-02-08 18:30:14 -05001641 c.writeRecord(recordTypeHandshake, postCCSBytes)
David Benjamin02edcd02016-07-27 17:40:37 -04001642 if c.config.Bugs.SendExtraFinished {
1643 c.writeRecord(recordTypeHandshake, finished.marshal())
1644 }
1645
David Benjamin12d2c482016-07-24 10:56:51 -04001646 if !c.config.Bugs.PackHelloRequestWithFinished {
1647 // Defer flushing until renegotiation.
1648 c.flushHandshake()
1649 }
David Benjaminb3774b92015-01-31 17:16:01 -05001650 }
Adam Langley95c29f32014-06-20 12:00:00 -07001651
David Benjaminc565ebb2015-04-03 04:06:36 -04001652 c.cipherSuite = hs.suite
Adam Langley95c29f32014-06-20 12:00:00 -07001653
1654 return nil
1655}
1656
1657// processCertsFromClient takes a chain of client certificates either from a
1658// Certificates message or from a sessionState and verifies them. It returns
1659// the public key of the leaf certificate.
1660func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
1661 c := hs.c
1662
1663 hs.certsFromClient = certificates
1664 certs := make([]*x509.Certificate, len(certificates))
1665 var err error
1666 for i, asn1Data := range certificates {
1667 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
1668 c.sendAlert(alertBadCertificate)
1669 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
1670 }
1671 }
1672
1673 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
1674 opts := x509.VerifyOptions{
1675 Roots: c.config.ClientCAs,
1676 CurrentTime: c.config.time(),
1677 Intermediates: x509.NewCertPool(),
1678 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
1679 }
1680
1681 for _, cert := range certs[1:] {
1682 opts.Intermediates.AddCert(cert)
1683 }
1684
1685 chains, err := certs[0].Verify(opts)
1686 if err != nil {
1687 c.sendAlert(alertBadCertificate)
1688 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
1689 }
1690
1691 ok := false
1692 for _, ku := range certs[0].ExtKeyUsage {
1693 if ku == x509.ExtKeyUsageClientAuth {
1694 ok = true
1695 break
1696 }
1697 }
1698 if !ok {
1699 c.sendAlert(alertHandshakeFailure)
1700 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
1701 }
1702
1703 c.verifiedChains = chains
1704 }
1705
1706 if len(certs) > 0 {
1707 var pub crypto.PublicKey
1708 switch key := certs[0].PublicKey.(type) {
1709 case *ecdsa.PublicKey, *rsa.PublicKey:
1710 pub = key
1711 default:
1712 c.sendAlert(alertUnsupportedCertificate)
1713 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
1714 }
1715 c.peerCertificates = certs
1716 return pub, nil
1717 }
1718
1719 return nil, nil
1720}
1721
David Benjamin83c0bc92014-08-04 01:23:53 -04001722func (hs *serverHandshakeState) writeServerHash(msg []byte) {
1723 // writeServerHash is called before writeRecord.
1724 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1725}
1726
1727func (hs *serverHandshakeState) writeClientHash(msg []byte) {
1728 // writeClientHash is called after readHandshake.
1729 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1730}
1731
1732func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
1733 if hs.c.isDTLS {
1734 // This is somewhat hacky. DTLS hashes a slightly different format.
1735 // First, the TLS header.
1736 hs.finishedHash.Write(msg[:4])
1737 // Then the sequence number and reassembled fragment offset (always 0).
1738 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1739 // Then the reassembled fragment (always equal to the message length).
1740 hs.finishedHash.Write(msg[1:4])
1741 // And then the message body.
1742 hs.finishedHash.Write(msg[4:])
1743 } else {
1744 hs.finishedHash.Write(msg)
1745 }
1746}
1747
Adam Langley95c29f32014-06-20 12:00:00 -07001748// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
1749// is acceptable to use.
Steven Valdez803c77a2016-09-06 14:13:43 -04001750func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
Adam Langley95c29f32014-06-20 12:00:00 -07001751 for _, supported := range supportedCipherSuites {
1752 if id == supported {
1753 var candidate *cipherSuite
1754
1755 for _, s := range cipherSuites {
1756 if s.id == id {
1757 candidate = s
1758 break
1759 }
1760 }
1761 if candidate == nil {
1762 continue
1763 }
Steven Valdez803c77a2016-09-06 14:13:43 -04001764
Adam Langley95c29f32014-06-20 12:00:00 -07001765 // Don't select a ciphersuite which we can't
1766 // support for this client.
Steven Valdez803c77a2016-09-06 14:13:43 -04001767 if version >= VersionTLS13 || candidate.flags&suiteTLS13 != 0 {
1768 if version < VersionTLS13 || candidate.flags&suiteTLS13 == 0 {
1769 continue
1770 }
1771 return candidate
David Benjamin5ecb88b2016-10-04 17:51:35 -04001772 }
1773 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
1774 continue
1775 }
1776 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
1777 continue
1778 }
1779 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
1780 continue
1781 }
David Benjamin5ecb88b2016-10-04 17:51:35 -04001782 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
1783 continue
David Benjamin83c0bc92014-08-04 01:23:53 -04001784 }
Adam Langley95c29f32014-06-20 12:00:00 -07001785 return candidate
1786 }
1787 }
1788
1789 return nil
1790}
David Benjaminf93995b2015-11-05 18:23:20 -05001791
1792func isTLS12Cipher(id uint16) bool {
1793 for _, cipher := range cipherSuites {
1794 if cipher.id != id {
1795 continue
1796 }
1797 return cipher.flags&suiteTLS12 != 0
1798 }
1799 // Unknown cipher.
1800 return false
1801}
David Benjamin65ac9972016-09-02 21:35:25 -04001802
1803func isGREASEValue(val uint16) bool {
David Benjamin3c6a1ea2016-09-26 18:30:05 -04001804 return val&0x0f0f == 0x0a0a && val&0xff == val>>8
David Benjamin65ac9972016-09-02 21:35:25 -04001805}