blob: 59b34faa65f593c512379da3169d6daec6b2ce10 [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 Benjamin490469f2016-10-05 22:44:38 -0400362 isDTLS: c.isDTLS,
363 vers: versionToWire(c.vers, c.isDTLS),
364 versOverride: config.Bugs.SendServerHelloVersion,
365 customExtension: config.Bugs.CustomUnencryptedExtension,
366 unencryptedALPN: config.Bugs.SendUnencryptedALPN,
Steven Valdez5440fe02016-07-18 12:40:30 -0400367 }
368
Nick Harper728eed82016-07-07 17:36:52 -0700369 hs.hello.random = make([]byte, 32)
370 if _, err := io.ReadFull(config.rand(), hs.hello.random); err != nil {
371 c.sendAlert(alertInternalError)
372 return err
373 }
374
375 // TLS 1.3 forbids clients from advertising any non-null compression.
376 if len(hs.clientHello.compressionMethods) != 1 || hs.clientHello.compressionMethods[0] != compressionNone {
377 return errors.New("tls: client sent compression method other than null for TLS 1.3")
378 }
379
380 // Prepare an EncryptedExtensions message, but do not send it yet.
381 encryptedExtensions := new(encryptedExtensionsMsg)
Steven Valdez143e8b32016-07-11 13:19:03 -0400382 encryptedExtensions.empty = config.Bugs.EmptyEncryptedExtensions
Nick Harper728eed82016-07-07 17:36:52 -0700383 if err := hs.processClientExtensions(&encryptedExtensions.extensions); err != nil {
384 return err
385 }
386
387 supportedCurve := false
388 var selectedCurve CurveID
389 preferredCurves := config.curvePreferences()
390Curves:
391 for _, curve := range hs.clientHello.supportedCurves {
392 for _, supported := range preferredCurves {
393 if supported == curve {
394 supportedCurve = true
395 selectedCurve = curve
396 break Curves
397 }
398 }
399 }
400
Steven Valdez803c77a2016-09-06 14:13:43 -0400401 if !supportedCurve {
402 c.sendAlert(alertHandshakeFailure)
403 return errors.New("tls: no curve supported by both client and server")
404 }
Nick Harper728eed82016-07-07 17:36:52 -0700405
David Benjamin405da482016-08-08 17:25:07 -0400406 pskIdentities := hs.clientHello.pskIdentities
407 if len(pskIdentities) == 0 && len(hs.clientHello.sessionTicket) > 0 && c.config.Bugs.AcceptAnySession {
Steven Valdez5b986082016-09-01 12:29:49 -0400408 psk := pskIdentity{
409 keModes: []byte{pskDHEKEMode},
410 authModes: []byte{pskAuthMode},
411 ticket: hs.clientHello.sessionTicket,
412 }
413 pskIdentities = []pskIdentity{psk}
David Benjamin405da482016-08-08 17:25:07 -0400414 }
415 for i, pskIdentity := range pskIdentities {
Steven Valdez5b986082016-09-01 12:29:49 -0400416 foundKE := false
417 foundAuth := false
418
419 for _, keMode := range pskIdentity.keModes {
420 if keMode == pskDHEKEMode {
421 foundKE = true
422 }
423 }
424
425 for _, authMode := range pskIdentity.authModes {
426 if authMode == pskAuthMode {
427 foundAuth = true
428 }
429 }
430
431 if !foundKE || !foundAuth {
432 continue
433 }
434
435 sessionState, ok := c.decryptTicket(pskIdentity.ticket)
Nick Harper0b3625b2016-07-25 16:16:28 -0700436 if !ok {
437 continue
438 }
Steven Valdez803c77a2016-09-06 14:13:43 -0400439 if config.Bugs.AcceptAnySession {
440 // Replace the cipher suite with one known to work, to
441 // test cross-version resumption attempts.
442 sessionState.cipherSuite = TLS_AES_128_GCM_SHA256
443 } else {
David Benjamin405da482016-08-08 17:25:07 -0400444 if sessionState.vers != c.vers && c.config.Bugs.AcceptAnySession {
445 continue
446 }
David Benjamin405da482016-08-08 17:25:07 -0400447 if sessionState.ticketExpiration.Before(c.config.time()) {
448 continue
449 }
David Benjamin405da482016-08-08 17:25:07 -0400450
Steven Valdez803c77a2016-09-06 14:13:43 -0400451 cipherSuiteOk := false
452 // Check that the client is still offering the ciphersuite in the session.
453 for _, id := range hs.clientHello.cipherSuites {
454 if id == sessionState.cipherSuite {
455 cipherSuiteOk = true
456 break
457 }
458 }
459 if !cipherSuiteOk {
460 continue
Nick Harper0b3625b2016-07-25 16:16:28 -0700461 }
462 }
David Benjamin405da482016-08-08 17:25:07 -0400463
Steven Valdez803c77a2016-09-06 14:13:43 -0400464 // Check that we also support the ciphersuite from the session.
465 suite := c.tryCipherSuite(sessionState.cipherSuite, c.config.cipherSuites(), c.vers, true, true)
466 if suite == nil {
467 continue
Nick Harper0b3625b2016-07-25 16:16:28 -0700468 }
Steven Valdez803c77a2016-09-06 14:13:43 -0400469
470 hs.sessionState = sessionState
471 hs.suite = suite
472 hs.hello.hasPSKIdentity = true
473 hs.hello.pskIdentity = uint16(i)
David Benjamin7f78df42016-10-05 22:33:19 -0400474 if config.Bugs.SelectPSKIdentityOnResume != 0 {
475 hs.hello.pskIdentity = config.Bugs.SelectPSKIdentityOnResume
476 }
Steven Valdez803c77a2016-09-06 14:13:43 -0400477 c.didResume = true
478 break
Nick Harper728eed82016-07-07 17:36:52 -0700479 }
480
David Benjamin7f78df42016-10-05 22:33:19 -0400481 if config.Bugs.AlwaysSelectPSKIdentity {
482 hs.hello.hasPSKIdentity = true
483 hs.hello.pskIdentity = 0
484 }
485
Nick Harper0b3625b2016-07-25 16:16:28 -0700486 // If not resuming, select the cipher suite.
487 if hs.suite == nil {
488 var preferenceList, supportedList []uint16
489 if config.PreferServerCipherSuites {
490 preferenceList = config.cipherSuites()
491 supportedList = hs.clientHello.cipherSuites
492 } else {
493 preferenceList = hs.clientHello.cipherSuites
494 supportedList = config.cipherSuites()
495 }
496
497 for _, id := range preferenceList {
Steven Valdez803c77a2016-09-06 14:13:43 -0400498 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, true, true); hs.suite != nil {
Nick Harper0b3625b2016-07-25 16:16:28 -0700499 break
500 }
Nick Harper728eed82016-07-07 17:36:52 -0700501 }
502 }
503
504 if hs.suite == nil {
505 c.sendAlert(alertHandshakeFailure)
506 return errors.New("tls: no cipher suite supported by both client and server")
507 }
508
509 hs.hello.cipherSuite = hs.suite.id
Steven Valdez0ee2e112016-07-15 06:51:15 -0400510 if c.config.Bugs.SendCipherSuite != 0 {
511 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
512 }
513
Nick Harper728eed82016-07-07 17:36:52 -0700514 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
515 hs.finishedHash.discardHandshakeBuffer()
516 hs.writeClientHash(hs.clientHello.marshal())
517
Steven Valdez803c77a2016-09-06 14:13:43 -0400518 hs.hello.useCertAuth = hs.sessionState == nil
519
Nick Harper728eed82016-07-07 17:36:52 -0700520 // Resolve PSK and compute the early secret.
Nick Harper0b3625b2016-07-25 16:16:28 -0700521 var psk []byte
Steven Valdez803c77a2016-09-06 14:13:43 -0400522 if hs.sessionState != nil {
Nick Harper0b3625b2016-07-25 16:16:28 -0700523 psk = deriveResumptionPSK(hs.suite, hs.sessionState.masterSecret)
524 hs.finishedHash.setResumptionContext(deriveResumptionContext(hs.suite, hs.sessionState.masterSecret))
525 } else {
526 psk = hs.finishedHash.zeroSecret()
527 hs.finishedHash.setResumptionContext(hs.finishedHash.zeroSecret())
528 }
Nick Harper728eed82016-07-07 17:36:52 -0700529
530 earlySecret := hs.finishedHash.extractKey(hs.finishedHash.zeroSecret(), psk)
531
Steven Valdez803c77a2016-09-06 14:13:43 -0400532 if config.Bugs.OmitServerHelloSignatureAlgorithms {
533 hs.hello.useCertAuth = false
534 } else if config.Bugs.IncludeServerHelloSignatureAlgorithms {
535 hs.hello.useCertAuth = true
536 }
537
538 hs.hello.hasKeyShare = true
539 if hs.sessionState != nil && config.Bugs.NegotiatePSKResumption {
540 hs.hello.hasKeyShare = false
541 }
542 if config.Bugs.MissingKeyShare {
543 hs.hello.hasKeyShare = false
544 }
545
Nick Harper728eed82016-07-07 17:36:52 -0700546 // Resolve ECDHE and compute the handshake secret.
547 var ecdheSecret []byte
Steven Valdez803c77a2016-09-06 14:13:43 -0400548 if hs.hello.hasKeyShare {
Nick Harper728eed82016-07-07 17:36:52 -0700549 // Look for the key share corresponding to our selected curve.
550 var selectedKeyShare *keyShareEntry
551 for i := range hs.clientHello.keyShares {
552 if hs.clientHello.keyShares[i].group == selectedCurve {
553 selectedKeyShare = &hs.clientHello.keyShares[i]
554 break
555 }
556 }
557
David Benjamine73c7f42016-08-17 00:29:33 -0400558 if config.Bugs.ExpectMissingKeyShare && selectedKeyShare != nil {
559 return errors.New("tls: expected missing key share")
560 }
561
Steven Valdez5440fe02016-07-18 12:40:30 -0400562 sendHelloRetryRequest := selectedKeyShare == nil
563 if config.Bugs.UnnecessaryHelloRetryRequest {
564 sendHelloRetryRequest = true
565 }
566 if config.Bugs.SkipHelloRetryRequest {
567 sendHelloRetryRequest = false
568 }
569 if sendHelloRetryRequest {
570 firstTime := true
571 ResendHelloRetryRequest:
Nick Harperdcfbc672016-07-16 17:47:31 +0200572 // Send HelloRetryRequest.
573 helloRetryRequestMsg := helloRetryRequestMsg{
Steven Valdezfdd10992016-09-15 16:27:05 -0400574 vers: versionToWire(c.vers, c.isDTLS),
Nick Harperdcfbc672016-07-16 17:47:31 +0200575 cipherSuite: hs.hello.cipherSuite,
576 selectedGroup: selectedCurve,
577 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400578 if config.Bugs.SendHelloRetryRequestCurve != 0 {
579 helloRetryRequestMsg.selectedGroup = config.Bugs.SendHelloRetryRequestCurve
580 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200581 hs.writeServerHash(helloRetryRequestMsg.marshal())
582 c.writeRecord(recordTypeHandshake, helloRetryRequestMsg.marshal())
David Benjamine73c7f42016-08-17 00:29:33 -0400583 c.flushHandshake()
Nick Harperdcfbc672016-07-16 17:47:31 +0200584
585 // Read new ClientHello.
586 newMsg, err := c.readHandshake()
587 if err != nil {
588 return err
589 }
590 newClientHello, ok := newMsg.(*clientHelloMsg)
591 if !ok {
592 c.sendAlert(alertUnexpectedMessage)
593 return unexpectedMessageError(newClientHello, newMsg)
594 }
595 hs.writeClientHash(newClientHello.marshal())
596
597 // Check that the new ClientHello matches the old ClientHello, except for
598 // the addition of the new KeyShareEntry at the end of the list, and
599 // removing the EarlyDataIndication extension (if present).
600 newKeyShares := newClientHello.keyShares
601 if len(newKeyShares) == 0 || newKeyShares[len(newKeyShares)-1].group != selectedCurve {
602 return errors.New("tls: KeyShare from HelloRetryRequest not present in new ClientHello")
603 }
604 oldClientHelloCopy := *hs.clientHello
605 oldClientHelloCopy.raw = nil
606 oldClientHelloCopy.hasEarlyData = false
607 oldClientHelloCopy.earlyDataContext = nil
608 newClientHelloCopy := *newClientHello
609 newClientHelloCopy.raw = nil
610 newClientHelloCopy.keyShares = newKeyShares[:len(newKeyShares)-1]
611 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
612 return errors.New("tls: new ClientHello does not match")
613 }
614
Steven Valdez5440fe02016-07-18 12:40:30 -0400615 if firstTime && config.Bugs.SecondHelloRetryRequest {
616 firstTime = false
617 goto ResendHelloRetryRequest
618 }
619
Nick Harperdcfbc672016-07-16 17:47:31 +0200620 selectedKeyShare = &newKeyShares[len(newKeyShares)-1]
Nick Harper728eed82016-07-07 17:36:52 -0700621 }
622
623 // Once a curve has been selected and a key share identified,
624 // the server needs to generate a public value and send it in
625 // the ServerHello.
Steven Valdez5440fe02016-07-18 12:40:30 -0400626 curve, ok := curveForCurveID(selectedCurve)
Nick Harper728eed82016-07-07 17:36:52 -0700627 if !ok {
628 panic("tls: server failed to look up curve ID")
629 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400630 c.curveID = selectedCurve
631
632 var peerKey []byte
633 if config.Bugs.SkipHelloRetryRequest {
634 // If skipping HelloRetryRequest, use a random key to
635 // avoid crashing.
636 curve2, _ := curveForCurveID(selectedCurve)
637 var err error
638 peerKey, err = curve2.offer(config.rand())
639 if err != nil {
640 return err
641 }
642 } else {
643 peerKey = selectedKeyShare.keyExchange
644 }
645
Nick Harper728eed82016-07-07 17:36:52 -0700646 var publicKey []byte
647 var err error
Steven Valdez5440fe02016-07-18 12:40:30 -0400648 publicKey, ecdheSecret, err = curve.accept(config.rand(), peerKey)
Nick Harper728eed82016-07-07 17:36:52 -0700649 if err != nil {
650 c.sendAlert(alertHandshakeFailure)
651 return err
652 }
653 hs.hello.hasKeyShare = true
Steven Valdez0ee2e112016-07-15 06:51:15 -0400654
Steven Valdez5440fe02016-07-18 12:40:30 -0400655 curveID := selectedCurve
Steven Valdez0ee2e112016-07-15 06:51:15 -0400656 if c.config.Bugs.SendCurve != 0 {
657 curveID = config.Bugs.SendCurve
658 }
659 if c.config.Bugs.InvalidECDHPoint {
660 publicKey[0] ^= 0xff
661 }
662
Nick Harper728eed82016-07-07 17:36:52 -0700663 hs.hello.keyShare = keyShareEntry{
Steven Valdez0ee2e112016-07-15 06:51:15 -0400664 group: curveID,
Nick Harper728eed82016-07-07 17:36:52 -0700665 keyExchange: publicKey,
666 }
Steven Valdez143e8b32016-07-11 13:19:03 -0400667
668 if config.Bugs.EncryptedExtensionsWithKeyShare {
669 encryptedExtensions.extensions.hasKeyShare = true
670 encryptedExtensions.extensions.keyShare = keyShareEntry{
671 group: curveID,
672 keyExchange: publicKey,
673 }
674 }
Nick Harper728eed82016-07-07 17:36:52 -0700675 } else {
676 ecdheSecret = hs.finishedHash.zeroSecret()
677 }
678
679 // Send unencrypted ServerHello.
680 hs.writeServerHash(hs.hello.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400681 if config.Bugs.PartialEncryptedExtensionsWithServerHello {
682 helloBytes := hs.hello.marshal()
683 toWrite := make([]byte, 0, len(helloBytes)+1)
684 toWrite = append(toWrite, helloBytes...)
685 toWrite = append(toWrite, typeEncryptedExtensions)
686 c.writeRecord(recordTypeHandshake, toWrite)
687 } else {
688 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
689 }
Nick Harper728eed82016-07-07 17:36:52 -0700690 c.flushHandshake()
691
692 // Compute the handshake secret.
693 handshakeSecret := hs.finishedHash.extractKey(earlySecret, ecdheSecret)
694
695 // Switch to handshake traffic keys.
696 handshakeTrafficSecret := hs.finishedHash.deriveSecret(handshakeSecret, handshakeTrafficLabel)
David Benjamin21c00282016-07-18 21:56:23 +0200697 c.out.useTrafficSecret(c.vers, hs.suite, handshakeTrafficSecret, handshakePhase, serverWrite)
698 c.in.useTrafficSecret(c.vers, hs.suite, handshakeTrafficSecret, handshakePhase, clientWrite)
Nick Harper728eed82016-07-07 17:36:52 -0700699
Steven Valdez803c77a2016-09-06 14:13:43 -0400700 if hs.hello.useCertAuth {
David Benjamin615119a2016-07-06 19:22:55 -0700701 if hs.clientHello.ocspStapling {
702 encryptedExtensions.extensions.ocspResponse = hs.cert.OCSPStaple
703 }
704 if hs.clientHello.sctListSupported {
705 encryptedExtensions.extensions.sctList = hs.cert.SignedCertificateTimestampList
706 }
David Benjamindaa88502016-10-04 16:32:16 -0400707 } else {
708 if config.Bugs.SendOCSPResponseOnResume != nil {
709 encryptedExtensions.extensions.ocspResponse = config.Bugs.SendOCSPResponseOnResume
710 }
711 if config.Bugs.SendSCTListOnResume != nil {
712 encryptedExtensions.extensions.sctList = config.Bugs.SendSCTListOnResume
713 }
David Benjamin615119a2016-07-06 19:22:55 -0700714 }
715
Nick Harper728eed82016-07-07 17:36:52 -0700716 // Send EncryptedExtensions.
717 hs.writeServerHash(encryptedExtensions.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400718 if config.Bugs.PartialEncryptedExtensionsWithServerHello {
719 // The first byte has already been sent.
720 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()[1:])
721 } else {
722 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal())
723 }
Nick Harper728eed82016-07-07 17:36:52 -0700724
Steven Valdez803c77a2016-09-06 14:13:43 -0400725 if hs.hello.useCertAuth {
Nick Harper728eed82016-07-07 17:36:52 -0700726 if config.ClientAuth >= RequestClientCert {
David Benjamin8d343b42016-07-09 14:26:01 -0700727 // Request a client certificate
728 certReq := &certificateRequestMsg{
729 hasSignatureAlgorithm: true,
730 hasRequestContext: true,
David Benjamin8a8349b2016-08-18 02:32:23 -0400731 requestContext: config.Bugs.SendRequestContext,
David Benjamin8d343b42016-07-09 14:26:01 -0700732 }
733 if !config.Bugs.NoSignatureAlgorithms {
David Benjaminf74ec792016-07-13 21:18:49 -0400734 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin8d343b42016-07-09 14:26:01 -0700735 }
736
737 // An empty list of certificateAuthorities signals to
738 // the client that it may send any certificate in response
739 // to our request. When we know the CAs we trust, then
740 // we can send them down, so that the client can choose
741 // an appropriate certificate to give to us.
742 if config.ClientCAs != nil {
743 certReq.certificateAuthorities = config.ClientCAs.Subjects()
744 }
745 hs.writeServerHash(certReq.marshal())
746 c.writeRecord(recordTypeHandshake, certReq.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700747 }
748
749 certMsg := &certificateMsg{
750 hasRequestContext: true,
751 }
752 if !config.Bugs.EmptyCertificateList {
753 certMsg.certificates = hs.cert.Certificate
754 }
David Benjamin1edae6b2016-07-13 16:58:23 -0400755 certMsgBytes := certMsg.marshal()
David Benjamin1edae6b2016-07-13 16:58:23 -0400756 hs.writeServerHash(certMsgBytes)
757 c.writeRecord(recordTypeHandshake, certMsgBytes)
Nick Harper728eed82016-07-07 17:36:52 -0700758
759 certVerify := &certificateVerifyMsg{
760 hasSignatureAlgorithm: true,
761 }
762
763 // Determine the hash to sign.
764 privKey := hs.cert.PrivateKey
765
766 var err error
767 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, config, hs.clientHello.signatureAlgorithms)
768 if err != nil {
769 c.sendAlert(alertInternalError)
770 return err
771 }
772
773 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
774 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
775 if err != nil {
776 c.sendAlert(alertInternalError)
777 return err
778 }
779
Steven Valdez0ee2e112016-07-15 06:51:15 -0400780 if config.Bugs.SendSignatureAlgorithm != 0 {
781 certVerify.signatureAlgorithm = config.Bugs.SendSignatureAlgorithm
782 }
783
Nick Harper728eed82016-07-07 17:36:52 -0700784 hs.writeServerHash(certVerify.marshal())
785 c.writeRecord(recordTypeHandshake, certVerify.marshal())
Steven Valdez803c77a2016-09-06 14:13:43 -0400786 } else if hs.sessionState != nil {
Nick Harper0b3625b2016-07-25 16:16:28 -0700787 // Pick up certificates from the session instead.
David Benjamin5ecb88b2016-10-04 17:51:35 -0400788 if len(hs.sessionState.certificates) > 0 {
Nick Harper0b3625b2016-07-25 16:16:28 -0700789 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
790 return err
791 }
792 }
Nick Harper728eed82016-07-07 17:36:52 -0700793 }
794
795 finished := new(finishedMsg)
796 finished.verifyData = hs.finishedHash.serverSum(handshakeTrafficSecret)
797 if config.Bugs.BadFinished {
798 finished.verifyData[0]++
799 }
800 hs.writeServerHash(finished.marshal())
801 c.writeRecord(recordTypeHandshake, finished.marshal())
David Benjamin02edcd02016-07-27 17:40:37 -0400802 if c.config.Bugs.SendExtraFinished {
803 c.writeRecord(recordTypeHandshake, finished.marshal())
804 }
Nick Harper728eed82016-07-07 17:36:52 -0700805 c.flushHandshake()
806
807 // The various secrets do not incorporate the client's final leg, so
808 // derive them now before updating the handshake context.
809 masterSecret := hs.finishedHash.extractKey(handshakeSecret, hs.finishedHash.zeroSecret())
810 trafficSecret := hs.finishedHash.deriveSecret(masterSecret, applicationTrafficLabel)
811
David Benjamin2aad4062016-07-14 23:15:40 -0400812 // Switch to application data keys on write. In particular, any alerts
813 // from the client certificate are sent over these keys.
David Benjamin21c00282016-07-18 21:56:23 +0200814 c.out.useTrafficSecret(c.vers, hs.suite, trafficSecret, applicationPhase, serverWrite)
David Benjamin2aad4062016-07-14 23:15:40 -0400815
Nick Harper728eed82016-07-07 17:36:52 -0700816 // If we requested a client certificate, then the client must send a
817 // certificate message, even if it's empty.
818 if config.ClientAuth >= RequestClientCert {
David Benjamin8d343b42016-07-09 14:26:01 -0700819 msg, err := c.readHandshake()
820 if err != nil {
821 return err
822 }
823
824 certMsg, ok := msg.(*certificateMsg)
825 if !ok {
826 c.sendAlert(alertUnexpectedMessage)
827 return unexpectedMessageError(certMsg, msg)
828 }
829 hs.writeClientHash(certMsg.marshal())
830
831 if len(certMsg.certificates) == 0 {
832 // The client didn't actually send a certificate
833 switch config.ClientAuth {
834 case RequireAnyClientCert, RequireAndVerifyClientCert:
David Benjamin1db9e1b2016-10-07 20:51:43 -0400835 c.sendAlert(alertCertificateRequired)
David Benjamin8d343b42016-07-09 14:26:01 -0700836 return errors.New("tls: client didn't provide a certificate")
837 }
838 }
839
840 pub, err := hs.processCertsFromClient(certMsg.certificates)
841 if err != nil {
842 return err
843 }
844
845 if len(c.peerCertificates) > 0 {
846 msg, err = c.readHandshake()
847 if err != nil {
848 return err
849 }
850
851 certVerify, ok := msg.(*certificateVerifyMsg)
852 if !ok {
853 c.sendAlert(alertUnexpectedMessage)
854 return unexpectedMessageError(certVerify, msg)
855 }
856
David Benjaminf74ec792016-07-13 21:18:49 -0400857 c.peerSignatureAlgorithm = certVerify.signatureAlgorithm
David Benjamin8d343b42016-07-09 14:26:01 -0700858 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
859 if err := verifyMessage(c.vers, pub, config, certVerify.signatureAlgorithm, input, certVerify.signature); err != nil {
860 c.sendAlert(alertBadCertificate)
861 return err
862 }
863 hs.writeClientHash(certVerify.marshal())
864 }
Nick Harper728eed82016-07-07 17:36:52 -0700865 }
866
867 // Read the client Finished message.
868 msg, err := c.readHandshake()
869 if err != nil {
870 return err
871 }
872 clientFinished, ok := msg.(*finishedMsg)
873 if !ok {
874 c.sendAlert(alertUnexpectedMessage)
875 return unexpectedMessageError(clientFinished, msg)
876 }
877
878 verify := hs.finishedHash.clientSum(handshakeTrafficSecret)
879 if len(verify) != len(clientFinished.verifyData) ||
880 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
881 c.sendAlert(alertHandshakeFailure)
882 return errors.New("tls: client's Finished message was incorrect")
883 }
David Benjamin97a0a082016-07-13 17:57:35 -0400884 hs.writeClientHash(clientFinished.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700885
David Benjamin2aad4062016-07-14 23:15:40 -0400886 // Switch to application data keys on read.
David Benjamin21c00282016-07-18 21:56:23 +0200887 c.in.useTrafficSecret(c.vers, hs.suite, trafficSecret, applicationPhase, clientWrite)
Nick Harper728eed82016-07-07 17:36:52 -0700888
Nick Harper728eed82016-07-07 17:36:52 -0700889 c.cipherSuite = hs.suite
David Benjamin97a0a082016-07-13 17:57:35 -0400890 c.exporterSecret = hs.finishedHash.deriveSecret(masterSecret, exporterLabel)
David Benjamin58104882016-07-18 01:25:41 +0200891 c.resumptionSecret = hs.finishedHash.deriveSecret(masterSecret, resumptionLabel)
892
893 // TODO(davidben): Allow configuring the number of tickets sent for
894 // testing.
895 if !c.config.SessionTicketsDisabled {
896 ticketCount := 2
897 for i := 0; i < ticketCount; i++ {
898 c.SendNewSessionTicket()
899 }
900 }
Nick Harper728eed82016-07-07 17:36:52 -0700901 return nil
902}
903
David Benjaminf25dda92016-07-04 10:05:26 -0700904// processClientHello processes the ClientHello message from the client and
905// decides whether we will perform session resumption.
906func (hs *serverHandshakeState) processClientHello() (isResume bool, err error) {
907 config := hs.c.config
908 c := hs.c
909
910 hs.hello = &serverHelloMsg{
911 isDTLS: c.isDTLS,
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400912 vers: versionToWire(c.vers, c.isDTLS),
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400913 versOverride: config.Bugs.SendServerHelloVersion,
David Benjaminf25dda92016-07-04 10:05:26 -0700914 compressionMethod: compressionNone,
915 }
916
917 hs.hello.random = make([]byte, 32)
918 _, err = io.ReadFull(config.rand(), hs.hello.random)
919 if err != nil {
920 c.sendAlert(alertInternalError)
921 return false, err
922 }
David Benjamin1f61f0d2016-07-10 12:20:35 -0400923 // Signal downgrades in the server random, per draft-ietf-tls-tls13-14,
924 // section 6.3.1.2.
Nick Harper85f20c22016-07-04 10:11:59 -0700925 if c.vers <= VersionTLS12 && config.maxVersion(c.isDTLS) >= VersionTLS13 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400926 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS13)
Nick Harper85f20c22016-07-04 10:11:59 -0700927 }
928 if c.vers <= VersionTLS11 && config.maxVersion(c.isDTLS) == VersionTLS12 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400929 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS12)
Nick Harper85f20c22016-07-04 10:11:59 -0700930 }
David Benjaminf25dda92016-07-04 10:05:26 -0700931
932 foundCompression := false
933 // We only support null compression, so check that the client offered it.
934 for _, compression := range hs.clientHello.compressionMethods {
935 if compression == compressionNone {
936 foundCompression = true
937 break
938 }
939 }
940
941 if !foundCompression {
942 c.sendAlert(alertHandshakeFailure)
943 return false, errors.New("tls: client does not support uncompressed connections")
944 }
David Benjamin7d79f832016-07-04 09:20:45 -0700945
946 if err := hs.processClientExtensions(&hs.hello.extensions); err != nil {
947 return false, err
Adam Langley09505632015-07-30 18:10:13 -0700948 }
Adam Langley95c29f32014-06-20 12:00:00 -0700949
950 supportedCurve := false
951 preferredCurves := config.curvePreferences()
952Curves:
953 for _, curve := range hs.clientHello.supportedCurves {
954 for _, supported := range preferredCurves {
955 if supported == curve {
956 supportedCurve = true
957 break Curves
958 }
959 }
960 }
961
962 supportedPointFormat := false
963 for _, pointFormat := range hs.clientHello.supportedPoints {
964 if pointFormat == pointFormatUncompressed {
965 supportedPointFormat = true
966 break
967 }
968 }
969 hs.ellipticOk = supportedCurve && supportedPointFormat
970
Adam Langley95c29f32014-06-20 12:00:00 -0700971 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
972
David Benjamin4b27d9f2015-05-12 22:42:52 -0400973 // For test purposes, check that the peer never offers a session when
974 // renegotiating.
975 if c.cipherSuite != nil && len(hs.clientHello.sessionId) > 0 && c.config.Bugs.FailIfResumeOnRenego {
976 return false, errors.New("tls: offered resumption on renegotiation")
977 }
978
David Benjamindd6fed92015-10-23 17:41:12 -0400979 if c.config.Bugs.FailIfSessionOffered && (len(hs.clientHello.sessionTicket) > 0 || len(hs.clientHello.sessionId) > 0) {
980 return false, errors.New("tls: client offered a session ticket or ID")
981 }
982
Adam Langley95c29f32014-06-20 12:00:00 -0700983 if hs.checkForResumption() {
984 return true, nil
985 }
986
Adam Langley95c29f32014-06-20 12:00:00 -0700987 var preferenceList, supportedList []uint16
988 if c.config.PreferServerCipherSuites {
989 preferenceList = c.config.cipherSuites()
990 supportedList = hs.clientHello.cipherSuites
991 } else {
992 preferenceList = hs.clientHello.cipherSuites
993 supportedList = c.config.cipherSuites()
994 }
995
996 for _, id := range preferenceList {
Steven Valdez803c77a2016-09-06 14:13:43 -0400997 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700998 break
999 }
1000 }
1001
1002 if hs.suite == nil {
1003 c.sendAlert(alertHandshakeFailure)
1004 return false, errors.New("tls: no cipher suite supported by both client and server")
1005 }
1006
1007 return false, nil
1008}
1009
David Benjamin7d79f832016-07-04 09:20:45 -07001010// processClientExtensions processes all ClientHello extensions not directly
1011// related to cipher suite negotiation and writes responses in serverExtensions.
1012func (hs *serverHandshakeState) processClientExtensions(serverExtensions *serverExtensions) error {
1013 config := hs.c.config
1014 c := hs.c
1015
David Benjamin8d315d72016-07-18 01:03:18 +02001016 if c.vers < VersionTLS13 || config.Bugs.NegotiateRenegotiationInfoAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -07001017 if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) {
1018 c.sendAlert(alertHandshakeFailure)
1019 return errors.New("tls: renegotiation mismatch")
David Benjamin7d79f832016-07-04 09:20:45 -07001020 }
David Benjamin7d79f832016-07-04 09:20:45 -07001021
Nick Harper728eed82016-07-07 17:36:52 -07001022 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
1023 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.clientVerify...)
1024 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.serverVerify...)
1025 if c.config.Bugs.BadRenegotiationInfo {
1026 serverExtensions.secureRenegotiation[0] ^= 0x80
1027 }
1028 } else {
1029 serverExtensions.secureRenegotiation = hs.clientHello.secureRenegotiation
1030 }
1031
1032 if c.noRenegotiationInfo() {
1033 serverExtensions.secureRenegotiation = nil
1034 }
David Benjamin7d79f832016-07-04 09:20:45 -07001035 }
1036
1037 serverExtensions.duplicateExtension = c.config.Bugs.DuplicateExtension
1038
1039 if len(hs.clientHello.serverName) > 0 {
1040 c.serverName = hs.clientHello.serverName
1041 }
1042 if len(config.Certificates) == 0 {
1043 c.sendAlert(alertInternalError)
1044 return errors.New("tls: no certificates configured")
1045 }
1046 hs.cert = &config.Certificates[0]
1047 if len(hs.clientHello.serverName) > 0 {
1048 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
1049 }
1050 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
1051 return errors.New("tls: unexpected server name")
1052 }
1053
1054 if len(hs.clientHello.alpnProtocols) > 0 {
1055 if proto := c.config.Bugs.ALPNProtocol; proto != nil {
1056 serverExtensions.alpnProtocol = *proto
1057 serverExtensions.alpnProtocolEmpty = len(*proto) == 0
1058 c.clientProtocol = *proto
1059 c.usedALPN = true
1060 } else if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
1061 serverExtensions.alpnProtocol = selectedProto
1062 c.clientProtocol = selectedProto
1063 c.usedALPN = true
1064 }
1065 }
Nick Harper728eed82016-07-07 17:36:52 -07001066
David Benjamin0c40a962016-08-01 12:05:50 -04001067 if len(c.config.Bugs.SendALPN) > 0 {
1068 serverExtensions.alpnProtocol = c.config.Bugs.SendALPN
1069 }
1070
David Benjamin8d315d72016-07-18 01:03:18 +02001071 if c.vers < VersionTLS13 || config.Bugs.NegotiateNPNAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -07001072 if len(hs.clientHello.alpnProtocols) == 0 || c.config.Bugs.NegotiateALPNAndNPN {
1073 // Although sending an empty NPN extension is reasonable, Firefox has
1074 // had a bug around this. Best to send nothing at all if
1075 // config.NextProtos is empty. See
1076 // https://code.google.com/p/go/issues/detail?id=5445.
1077 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
1078 serverExtensions.nextProtoNeg = true
1079 serverExtensions.nextProtos = config.NextProtos
1080 serverExtensions.npnLast = config.Bugs.SwapNPNAndALPN
1081 }
David Benjamin7d79f832016-07-04 09:20:45 -07001082 }
Steven Valdez143e8b32016-07-11 13:19:03 -04001083 }
David Benjamin7d79f832016-07-04 09:20:45 -07001084
David Benjamin8d315d72016-07-18 01:03:18 +02001085 if c.vers < VersionTLS13 || config.Bugs.NegotiateEMSAtAllVersions {
David Benjamin163c9562016-08-29 23:14:17 -04001086 disableEMS := config.Bugs.NoExtendedMasterSecret
1087 if c.cipherSuite != nil {
1088 disableEMS = config.Bugs.NoExtendedMasterSecretOnRenegotiation
1089 }
1090 serverExtensions.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !disableEMS
Steven Valdez143e8b32016-07-11 13:19:03 -04001091 }
David Benjamin7d79f832016-07-04 09:20:45 -07001092
David Benjamin8d315d72016-07-18 01:03:18 +02001093 if c.vers < VersionTLS13 || config.Bugs.NegotiateChannelIDAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -07001094 if hs.clientHello.channelIDSupported && config.RequestChannelID {
1095 serverExtensions.channelIDRequested = true
1096 }
David Benjamin7d79f832016-07-04 09:20:45 -07001097 }
1098
1099 if hs.clientHello.srtpProtectionProfiles != nil {
1100 SRTPLoop:
1101 for _, p1 := range c.config.SRTPProtectionProfiles {
1102 for _, p2 := range hs.clientHello.srtpProtectionProfiles {
1103 if p1 == p2 {
1104 serverExtensions.srtpProtectionProfile = p1
1105 c.srtpProtectionProfile = p1
1106 break SRTPLoop
1107 }
1108 }
1109 }
1110 }
1111
1112 if c.config.Bugs.SendSRTPProtectionProfile != 0 {
1113 serverExtensions.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
1114 }
1115
1116 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
1117 if hs.clientHello.customExtension != *expected {
1118 return fmt.Errorf("tls: bad custom extension contents %q", hs.clientHello.customExtension)
1119 }
1120 }
1121 serverExtensions.customExtension = config.Bugs.CustomExtension
1122
Steven Valdez143e8b32016-07-11 13:19:03 -04001123 if c.config.Bugs.AdvertiseTicketExtension {
1124 serverExtensions.ticketSupported = true
1125 }
1126
David Benjamin65ac9972016-09-02 21:35:25 -04001127 if !hs.clientHello.hasGREASEExtension && config.Bugs.ExpectGREASE {
1128 return errors.New("tls: no GREASE extension found")
1129 }
1130
David Benjamin7d79f832016-07-04 09:20:45 -07001131 return nil
1132}
1133
Adam Langley95c29f32014-06-20 12:00:00 -07001134// checkForResumption returns true if we should perform resumption on this connection.
1135func (hs *serverHandshakeState) checkForResumption() bool {
1136 c := hs.c
1137
David Benjamin405da482016-08-08 17:25:07 -04001138 ticket := hs.clientHello.sessionTicket
1139 if len(ticket) == 0 && len(hs.clientHello.pskIdentities) > 0 && c.config.Bugs.AcceptAnySession {
Steven Valdez5b986082016-09-01 12:29:49 -04001140 ticket = hs.clientHello.pskIdentities[0].ticket
David Benjamin405da482016-08-08 17:25:07 -04001141 }
1142 if len(ticket) > 0 {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001143 if c.config.SessionTicketsDisabled {
1144 return false
1145 }
David Benjaminb0c8db72014-09-24 15:19:56 -04001146
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001147 var ok bool
David Benjamin405da482016-08-08 17:25:07 -04001148 if hs.sessionState, ok = c.decryptTicket(ticket); !ok {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001149 return false
1150 }
1151 } else {
1152 if c.config.ServerSessionCache == nil {
1153 return false
1154 }
1155
1156 var ok bool
1157 sessionId := string(hs.clientHello.sessionId)
1158 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
1159 return false
1160 }
Adam Langley95c29f32014-06-20 12:00:00 -07001161 }
1162
Steven Valdez803c77a2016-09-06 14:13:43 -04001163 if c.config.Bugs.AcceptAnySession {
1164 // Replace the cipher suite with one known to work, to test
1165 // cross-version resumption attempts.
1166 hs.sessionState.cipherSuite = TLS_RSA_WITH_AES_128_CBC_SHA
1167 } else {
David Benjamin405da482016-08-08 17:25:07 -04001168 // Never resume a session for a different SSL version.
1169 if c.vers != hs.sessionState.vers {
1170 return false
Adam Langley95c29f32014-06-20 12:00:00 -07001171 }
David Benjamin405da482016-08-08 17:25:07 -04001172
1173 cipherSuiteOk := false
1174 // Check that the client is still offering the ciphersuite in the session.
1175 for _, id := range hs.clientHello.cipherSuites {
1176 if id == hs.sessionState.cipherSuite {
1177 cipherSuiteOk = true
1178 break
1179 }
1180 }
1181 if !cipherSuiteOk {
1182 return false
1183 }
Adam Langley95c29f32014-06-20 12:00:00 -07001184 }
1185
1186 // Check that we also support the ciphersuite from the session.
Steven Valdez803c77a2016-09-06 14:13:43 -04001187 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), c.vers, hs.ellipticOk, hs.ecdsaOk)
1188
Adam Langley95c29f32014-06-20 12:00:00 -07001189 if hs.suite == nil {
1190 return false
1191 }
1192
1193 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
1194 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
1195 if needClientCerts && !sessionHasClientCerts {
1196 return false
1197 }
1198 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
1199 return false
1200 }
1201
1202 return true
1203}
1204
1205func (hs *serverHandshakeState) doResumeHandshake() error {
1206 c := hs.c
1207
1208 hs.hello.cipherSuite = hs.suite.id
David Benjaminece3de92015-03-16 18:02:20 -04001209 if c.config.Bugs.SendCipherSuite != 0 {
1210 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
1211 }
Adam Langley95c29f32014-06-20 12:00:00 -07001212 // We echo the client's session ID in the ServerHello to let it know
1213 // that we're doing a resumption.
1214 hs.hello.sessionId = hs.clientHello.sessionId
Nick Harperb3d51be2016-07-01 11:43:18 -04001215 hs.hello.extensions.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -07001216
David Benjamin80d1b352016-05-04 19:19:06 -04001217 if c.config.Bugs.SendSCTListOnResume != nil {
Nick Harperb3d51be2016-07-01 11:43:18 -04001218 hs.hello.extensions.sctList = c.config.Bugs.SendSCTListOnResume
David Benjamin80d1b352016-05-04 19:19:06 -04001219 }
1220
David Benjamindaa88502016-10-04 16:32:16 -04001221 if c.config.Bugs.SendOCSPResponseOnResume != nil {
1222 // There is no way, syntactically, to send an OCSP response on a
1223 // resumption handshake.
1224 hs.hello.extensions.ocspStapling = true
1225 }
1226
Adam Langley95c29f32014-06-20 12:00:00 -07001227 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -04001228 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -04001229 hs.writeClientHash(hs.clientHello.marshal())
1230 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001231
1232 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
1233
1234 if len(hs.sessionState.certificates) > 0 {
1235 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
1236 return err
1237 }
1238 }
1239
1240 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -07001241 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -07001242
1243 return nil
1244}
1245
1246func (hs *serverHandshakeState) doFullHandshake() error {
1247 config := hs.c.config
1248 c := hs.c
1249
David Benjamin48cae082014-10-27 01:06:24 -04001250 isPSK := hs.suite.flags&suitePSK != 0
1251 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001252 hs.hello.extensions.ocspStapling = true
Adam Langley95c29f32014-06-20 12:00:00 -07001253 }
1254
David Benjamin61f95272014-11-25 01:55:35 -05001255 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001256 hs.hello.extensions.sctList = hs.cert.SignedCertificateTimestampList
David Benjamin61f95272014-11-25 01:55:35 -05001257 }
1258
Nick Harperb3d51be2016-07-01 11:43:18 -04001259 hs.hello.extensions.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
Adam Langley95c29f32014-06-20 12:00:00 -07001260 hs.hello.cipherSuite = hs.suite.id
David Benjamin6095de82014-12-27 01:50:38 -05001261 if config.Bugs.SendCipherSuite != 0 {
1262 hs.hello.cipherSuite = config.Bugs.SendCipherSuite
1263 }
Nick Harperb3d51be2016-07-01 11:43:18 -04001264 c.extendedMasterSecret = hs.hello.extensions.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -07001265
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001266 // Generate a session ID if we're to save the session.
Nick Harperb3d51be2016-07-01 11:43:18 -04001267 if !hs.hello.extensions.ticketSupported && config.ServerSessionCache != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001268 hs.hello.sessionId = make([]byte, 32)
1269 if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
1270 c.sendAlert(alertInternalError)
1271 return errors.New("tls: short read from Rand: " + err.Error())
1272 }
1273 }
1274
Adam Langley95c29f32014-06-20 12:00:00 -07001275 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -04001276 hs.writeClientHash(hs.clientHello.marshal())
1277 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001278
David Benjaminabe94e32016-09-04 14:18:58 -04001279 if config.Bugs.SendSNIWarningAlert {
1280 c.SendAlert(alertLevelWarning, alertUnrecognizedName)
1281 }
1282
Adam Langley95c29f32014-06-20 12:00:00 -07001283 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
1284
David Benjamin48cae082014-10-27 01:06:24 -04001285 if !isPSK {
1286 certMsg := new(certificateMsg)
David Benjamin8923c0b2015-06-07 11:42:34 -04001287 if !config.Bugs.EmptyCertificateList {
1288 certMsg.certificates = hs.cert.Certificate
1289 }
David Benjamin48cae082014-10-27 01:06:24 -04001290 if !config.Bugs.UnauthenticatedECDH {
David Benjaminbcb2d912015-02-24 23:45:43 -05001291 certMsgBytes := certMsg.marshal()
David Benjaminbcb2d912015-02-24 23:45:43 -05001292 hs.writeServerHash(certMsgBytes)
1293 c.writeRecord(recordTypeHandshake, certMsgBytes)
David Benjamin48cae082014-10-27 01:06:24 -04001294 }
David Benjamin1c375dd2014-07-12 00:48:23 -04001295 }
Adam Langley95c29f32014-06-20 12:00:00 -07001296
Nick Harperb3d51be2016-07-01 11:43:18 -04001297 if hs.hello.extensions.ocspStapling && !c.config.Bugs.SkipCertificateStatus {
Adam Langley95c29f32014-06-20 12:00:00 -07001298 certStatus := new(certificateStatusMsg)
1299 certStatus.statusType = statusTypeOCSP
1300 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -04001301 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001302 c.writeRecord(recordTypeHandshake, certStatus.marshal())
1303 }
1304
1305 keyAgreement := hs.suite.ka(c.vers)
1306 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
1307 if err != nil {
1308 c.sendAlert(alertHandshakeFailure)
1309 return err
1310 }
Steven Valdez5440fe02016-07-18 12:40:30 -04001311 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
1312 c.curveID = ecdhe.curveID
1313 }
David Benjamin9c651c92014-07-12 13:27:45 -04001314 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -04001315 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001316 c.writeRecord(recordTypeHandshake, skx.marshal())
1317 }
1318
1319 if config.ClientAuth >= RequestClientCert {
1320 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -04001321 certReq := &certificateRequestMsg{
1322 certificateTypes: config.ClientCertificateTypes,
1323 }
1324 if certReq.certificateTypes == nil {
1325 certReq.certificateTypes = []byte{
1326 byte(CertTypeRSASign),
1327 byte(CertTypeECDSASign),
1328 }
Adam Langley95c29f32014-06-20 12:00:00 -07001329 }
1330 if c.vers >= VersionTLS12 {
Nick Harper60edffd2016-06-21 15:19:24 -07001331 certReq.hasSignatureAlgorithm = true
1332 if !config.Bugs.NoSignatureAlgorithms {
David Benjamin7a41d372016-07-09 11:21:54 -07001333 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin000800a2014-11-14 01:43:59 -05001334 }
Adam Langley95c29f32014-06-20 12:00:00 -07001335 }
1336
1337 // An empty list of certificateAuthorities signals to
1338 // the client that it may send any certificate in response
1339 // to our request. When we know the CAs we trust, then
1340 // we can send them down, so that the client can choose
1341 // an appropriate certificate to give to us.
1342 if config.ClientCAs != nil {
1343 certReq.certificateAuthorities = config.ClientCAs.Subjects()
1344 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001345 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001346 c.writeRecord(recordTypeHandshake, certReq.marshal())
1347 }
1348
1349 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001350 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001351 c.writeRecord(recordTypeHandshake, helloDone.marshal())
David Benjamin582ba042016-07-07 12:33:25 -07001352 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001353
1354 var pub crypto.PublicKey // public key for client auth, if any
1355
David Benjamin83f90402015-01-27 01:09:43 -05001356 if err := c.simulatePacketLoss(nil); err != nil {
1357 return err
1358 }
Adam Langley95c29f32014-06-20 12:00:00 -07001359 msg, err := c.readHandshake()
1360 if err != nil {
1361 return err
1362 }
1363
1364 var ok bool
1365 // If we requested a client certificate, then the client must send a
1366 // certificate message, even if it's empty.
1367 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -04001368 var certMsg *certificateMsg
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001369 var certificates [][]byte
1370 if certMsg, ok = msg.(*certificateMsg); ok {
1371 if c.vers == VersionSSL30 && len(certMsg.certificates) == 0 {
1372 return errors.New("tls: empty certificate message in SSL 3.0")
1373 }
1374
1375 hs.writeClientHash(certMsg.marshal())
1376 certificates = certMsg.certificates
1377 } else if c.vers != VersionSSL30 {
1378 // In TLS, the Certificate message is required. In SSL
1379 // 3.0, the peer skips it when sending no certificates.
Adam Langley95c29f32014-06-20 12:00:00 -07001380 c.sendAlert(alertUnexpectedMessage)
1381 return unexpectedMessageError(certMsg, msg)
1382 }
Adam Langley95c29f32014-06-20 12:00:00 -07001383
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001384 if len(certificates) == 0 {
Adam Langley95c29f32014-06-20 12:00:00 -07001385 // The client didn't actually send a certificate
1386 switch config.ClientAuth {
1387 case RequireAnyClientCert, RequireAndVerifyClientCert:
1388 c.sendAlert(alertBadCertificate)
1389 return errors.New("tls: client didn't provide a certificate")
1390 }
1391 }
1392
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001393 pub, err = hs.processCertsFromClient(certificates)
Adam Langley95c29f32014-06-20 12:00:00 -07001394 if err != nil {
1395 return err
1396 }
1397
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001398 if ok {
1399 msg, err = c.readHandshake()
1400 if err != nil {
1401 return err
1402 }
Adam Langley95c29f32014-06-20 12:00:00 -07001403 }
1404 }
1405
1406 // Get client key exchange
1407 ckx, ok := msg.(*clientKeyExchangeMsg)
1408 if !ok {
1409 c.sendAlert(alertUnexpectedMessage)
1410 return unexpectedMessageError(ckx, msg)
1411 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001412 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001413
David Benjamine098ec22014-08-27 23:13:20 -04001414 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
1415 if err != nil {
1416 c.sendAlert(alertHandshakeFailure)
1417 return err
1418 }
Adam Langley75712922014-10-10 16:23:43 -07001419 if c.extendedMasterSecret {
1420 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1421 } else {
1422 if c.config.Bugs.RequireExtendedMasterSecret {
1423 return errors.New("tls: extended master secret required but not supported by peer")
1424 }
1425 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
1426 }
David Benjamine098ec22014-08-27 23:13:20 -04001427
Adam Langley95c29f32014-06-20 12:00:00 -07001428 // If we received a client cert in response to our certificate request message,
1429 // the client will send us a certificateVerifyMsg immediately after the
1430 // clientKeyExchangeMsg. This message is a digest of all preceding
1431 // handshake-layer messages that is signed using the private key corresponding
1432 // to the client's certificate. This allows us to verify that the client is in
1433 // possession of the private key of the certificate.
1434 if len(c.peerCertificates) > 0 {
1435 msg, err = c.readHandshake()
1436 if err != nil {
1437 return err
1438 }
1439 certVerify, ok := msg.(*certificateVerifyMsg)
1440 if !ok {
1441 c.sendAlert(alertUnexpectedMessage)
1442 return unexpectedMessageError(certVerify, msg)
1443 }
1444
David Benjaminde620d92014-07-18 15:03:41 -04001445 // Determine the signature type.
Nick Harper60edffd2016-06-21 15:19:24 -07001446 var sigAlg signatureAlgorithm
1447 if certVerify.hasSignatureAlgorithm {
1448 sigAlg = certVerify.signatureAlgorithm
Nick Harper60edffd2016-06-21 15:19:24 -07001449 c.peerSignatureAlgorithm = sigAlg
David Benjaminde620d92014-07-18 15:03:41 -04001450 }
1451
Nick Harper60edffd2016-06-21 15:19:24 -07001452 if c.vers > VersionSSL30 {
David Benjamin1fb125c2016-07-08 18:52:12 -07001453 err = verifyMessage(c.vers, pub, c.config, sigAlg, hs.finishedHash.buffer, certVerify.signature)
Nick Harper60edffd2016-06-21 15:19:24 -07001454 } else {
1455 // SSL 3.0's client certificate construction is
1456 // incompatible with signatureAlgorithm.
1457 rsaPub, ok := pub.(*rsa.PublicKey)
1458 if !ok {
1459 err = errors.New("unsupported key type for client certificate")
1460 } else {
1461 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
1462 err = rsa.VerifyPKCS1v15(rsaPub, crypto.MD5SHA1, digest, certVerify.signature)
David Benjaminde620d92014-07-18 15:03:41 -04001463 }
Adam Langley95c29f32014-06-20 12:00:00 -07001464 }
1465 if err != nil {
1466 c.sendAlert(alertBadCertificate)
1467 return errors.New("could not validate signature of connection nonces: " + err.Error())
1468 }
1469
David Benjamin83c0bc92014-08-04 01:23:53 -04001470 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001471 }
1472
David Benjamine098ec22014-08-27 23:13:20 -04001473 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001474
1475 return nil
1476}
1477
1478func (hs *serverHandshakeState) establishKeys() error {
1479 c := hs.c
1480
1481 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001482 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 -07001483
1484 var clientCipher, serverCipher interface{}
1485 var clientHash, serverHash macFunction
1486
1487 if hs.suite.aead == nil {
1488 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
1489 clientHash = hs.suite.mac(c.vers, clientMAC)
1490 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
1491 serverHash = hs.suite.mac(c.vers, serverMAC)
1492 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001493 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1494 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001495 }
1496
1497 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
1498 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
1499
1500 return nil
1501}
1502
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001503func (hs *serverHandshakeState) readFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001504 c := hs.c
1505
1506 c.readRecord(recordTypeChangeCipherSpec)
1507 if err := c.in.error(); err != nil {
1508 return err
1509 }
1510
Nick Harperb3d51be2016-07-01 11:43:18 -04001511 if hs.hello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001512 msg, err := c.readHandshake()
1513 if err != nil {
1514 return err
1515 }
1516 nextProto, ok := msg.(*nextProtoMsg)
1517 if !ok {
1518 c.sendAlert(alertUnexpectedMessage)
1519 return unexpectedMessageError(nextProto, msg)
1520 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001521 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001522 c.clientProtocol = nextProto.proto
1523 }
1524
Nick Harperb3d51be2016-07-01 11:43:18 -04001525 if hs.hello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001526 msg, err := c.readHandshake()
1527 if err != nil {
1528 return err
1529 }
David Benjamin24599a82016-06-30 18:56:53 -04001530 channelIDMsg, ok := msg.(*channelIDMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001531 if !ok {
1532 c.sendAlert(alertUnexpectedMessage)
David Benjamin24599a82016-06-30 18:56:53 -04001533 return unexpectedMessageError(channelIDMsg, msg)
David Benjamind30a9902014-08-24 01:44:23 -04001534 }
David Benjamin24599a82016-06-30 18:56:53 -04001535 x := new(big.Int).SetBytes(channelIDMsg.channelID[0:32])
1536 y := new(big.Int).SetBytes(channelIDMsg.channelID[32:64])
1537 r := new(big.Int).SetBytes(channelIDMsg.channelID[64:96])
1538 s := new(big.Int).SetBytes(channelIDMsg.channelID[96:128])
David Benjamind30a9902014-08-24 01:44:23 -04001539 if !elliptic.P256().IsOnCurve(x, y) {
1540 return errors.New("tls: invalid channel ID public key")
1541 }
1542 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
1543 var resumeHash []byte
1544 if isResume {
1545 resumeHash = hs.sessionState.handshakeHash
1546 }
1547 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
1548 return errors.New("tls: invalid channel ID signature")
1549 }
1550 c.channelID = channelID
1551
David Benjamin24599a82016-06-30 18:56:53 -04001552 hs.writeClientHash(channelIDMsg.marshal())
David Benjamind30a9902014-08-24 01:44:23 -04001553 }
1554
Adam Langley95c29f32014-06-20 12:00:00 -07001555 msg, err := c.readHandshake()
1556 if err != nil {
1557 return err
1558 }
1559 clientFinished, ok := msg.(*finishedMsg)
1560 if !ok {
1561 c.sendAlert(alertUnexpectedMessage)
1562 return unexpectedMessageError(clientFinished, msg)
1563 }
1564
1565 verify := hs.finishedHash.clientSum(hs.masterSecret)
1566 if len(verify) != len(clientFinished.verifyData) ||
1567 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
1568 c.sendAlert(alertHandshakeFailure)
1569 return errors.New("tls: client's Finished message is incorrect")
1570 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001571 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001572 copy(out, clientFinished.verifyData)
Adam Langley95c29f32014-06-20 12:00:00 -07001573
David Benjamin83c0bc92014-08-04 01:23:53 -04001574 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001575 return nil
1576}
1577
1578func (hs *serverHandshakeState) sendSessionTicket() error {
Adam Langley95c29f32014-06-20 12:00:00 -07001579 c := hs.c
Adam Langley95c29f32014-06-20 12:00:00 -07001580 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -04001581 vers: c.vers,
1582 cipherSuite: hs.suite.id,
1583 masterSecret: hs.masterSecret,
1584 certificates: hs.certsFromClient,
1585 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -07001586 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001587
Nick Harperb3d51be2016-07-01 11:43:18 -04001588 if !hs.hello.extensions.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001589 if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
1590 c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
1591 }
1592 return nil
1593 }
1594
1595 m := new(newSessionTicketMsg)
1596
David Benjamindd6fed92015-10-23 17:41:12 -04001597 if !c.config.Bugs.SendEmptySessionTicket {
1598 var err error
1599 m.ticket, err = c.encryptTicket(&state)
1600 if err != nil {
1601 return err
1602 }
Adam Langley95c29f32014-06-20 12:00:00 -07001603 }
Adam Langley95c29f32014-06-20 12:00:00 -07001604
David Benjamin83c0bc92014-08-04 01:23:53 -04001605 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001606 c.writeRecord(recordTypeHandshake, m.marshal())
1607
1608 return nil
1609}
1610
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001611func (hs *serverHandshakeState) sendFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001612 c := hs.c
1613
David Benjamin86271ee2014-07-21 16:14:03 -04001614 finished := new(finishedMsg)
1615 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001616 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001617 if c.config.Bugs.BadFinished {
1618 finished.verifyData[0]++
1619 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001620 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001621 hs.finishedBytes = finished.marshal()
1622 hs.writeServerHash(hs.finishedBytes)
1623 postCCSBytes := hs.finishedBytes
David Benjamin86271ee2014-07-21 16:14:03 -04001624
1625 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
1626 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
1627 postCCSBytes = postCCSBytes[5:]
David Benjamin61672812016-07-14 23:10:43 -04001628 } else if c.config.Bugs.SendUnencryptedFinished {
1629 c.writeRecord(recordTypeHandshake, postCCSBytes)
1630 postCCSBytes = nil
David Benjamin86271ee2014-07-21 16:14:03 -04001631 }
David Benjamin582ba042016-07-07 12:33:25 -07001632 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001633
David Benjamina0e52232014-07-19 17:39:58 -04001634 if !c.config.Bugs.SkipChangeCipherSpec {
David Benjamin8411b242015-11-26 12:07:28 -05001635 ccs := []byte{1}
1636 if c.config.Bugs.BadChangeCipherSpec != nil {
1637 ccs = c.config.Bugs.BadChangeCipherSpec
1638 }
1639 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamina0e52232014-07-19 17:39:58 -04001640 }
Adam Langley95c29f32014-06-20 12:00:00 -07001641
David Benjamin4189bd92015-01-25 23:52:39 -05001642 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1643 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1644 }
David Benjamindc3da932015-03-12 15:09:02 -04001645 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1646 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1647 return errors.New("tls: simulating post-CCS alert")
1648 }
David Benjamin4189bd92015-01-25 23:52:39 -05001649
David Benjamin61672812016-07-14 23:10:43 -04001650 if !c.config.Bugs.SkipFinished && len(postCCSBytes) > 0 {
David Benjaminb80168e2015-02-08 18:30:14 -05001651 c.writeRecord(recordTypeHandshake, postCCSBytes)
David Benjamin02edcd02016-07-27 17:40:37 -04001652 if c.config.Bugs.SendExtraFinished {
1653 c.writeRecord(recordTypeHandshake, finished.marshal())
1654 }
1655
David Benjamin12d2c482016-07-24 10:56:51 -04001656 if !c.config.Bugs.PackHelloRequestWithFinished {
1657 // Defer flushing until renegotiation.
1658 c.flushHandshake()
1659 }
David Benjaminb3774b92015-01-31 17:16:01 -05001660 }
Adam Langley95c29f32014-06-20 12:00:00 -07001661
David Benjaminc565ebb2015-04-03 04:06:36 -04001662 c.cipherSuite = hs.suite
Adam Langley95c29f32014-06-20 12:00:00 -07001663
1664 return nil
1665}
1666
1667// processCertsFromClient takes a chain of client certificates either from a
1668// Certificates message or from a sessionState and verifies them. It returns
1669// the public key of the leaf certificate.
1670func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
1671 c := hs.c
1672
1673 hs.certsFromClient = certificates
1674 certs := make([]*x509.Certificate, len(certificates))
1675 var err error
1676 for i, asn1Data := range certificates {
1677 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
1678 c.sendAlert(alertBadCertificate)
1679 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
1680 }
1681 }
1682
1683 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
1684 opts := x509.VerifyOptions{
1685 Roots: c.config.ClientCAs,
1686 CurrentTime: c.config.time(),
1687 Intermediates: x509.NewCertPool(),
1688 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
1689 }
1690
1691 for _, cert := range certs[1:] {
1692 opts.Intermediates.AddCert(cert)
1693 }
1694
1695 chains, err := certs[0].Verify(opts)
1696 if err != nil {
1697 c.sendAlert(alertBadCertificate)
1698 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
1699 }
1700
1701 ok := false
1702 for _, ku := range certs[0].ExtKeyUsage {
1703 if ku == x509.ExtKeyUsageClientAuth {
1704 ok = true
1705 break
1706 }
1707 }
1708 if !ok {
1709 c.sendAlert(alertHandshakeFailure)
1710 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
1711 }
1712
1713 c.verifiedChains = chains
1714 }
1715
1716 if len(certs) > 0 {
1717 var pub crypto.PublicKey
1718 switch key := certs[0].PublicKey.(type) {
1719 case *ecdsa.PublicKey, *rsa.PublicKey:
1720 pub = key
1721 default:
1722 c.sendAlert(alertUnsupportedCertificate)
1723 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
1724 }
1725 c.peerCertificates = certs
1726 return pub, nil
1727 }
1728
1729 return nil, nil
1730}
1731
David Benjamin83c0bc92014-08-04 01:23:53 -04001732func (hs *serverHandshakeState) writeServerHash(msg []byte) {
1733 // writeServerHash is called before writeRecord.
1734 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1735}
1736
1737func (hs *serverHandshakeState) writeClientHash(msg []byte) {
1738 // writeClientHash is called after readHandshake.
1739 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1740}
1741
1742func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
1743 if hs.c.isDTLS {
1744 // This is somewhat hacky. DTLS hashes a slightly different format.
1745 // First, the TLS header.
1746 hs.finishedHash.Write(msg[:4])
1747 // Then the sequence number and reassembled fragment offset (always 0).
1748 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1749 // Then the reassembled fragment (always equal to the message length).
1750 hs.finishedHash.Write(msg[1:4])
1751 // And then the message body.
1752 hs.finishedHash.Write(msg[4:])
1753 } else {
1754 hs.finishedHash.Write(msg)
1755 }
1756}
1757
Adam Langley95c29f32014-06-20 12:00:00 -07001758// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
1759// is acceptable to use.
Steven Valdez803c77a2016-09-06 14:13:43 -04001760func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
Adam Langley95c29f32014-06-20 12:00:00 -07001761 for _, supported := range supportedCipherSuites {
1762 if id == supported {
1763 var candidate *cipherSuite
1764
1765 for _, s := range cipherSuites {
1766 if s.id == id {
1767 candidate = s
1768 break
1769 }
1770 }
1771 if candidate == nil {
1772 continue
1773 }
Steven Valdez803c77a2016-09-06 14:13:43 -04001774
Adam Langley95c29f32014-06-20 12:00:00 -07001775 // Don't select a ciphersuite which we can't
1776 // support for this client.
Steven Valdez803c77a2016-09-06 14:13:43 -04001777 if version >= VersionTLS13 || candidate.flags&suiteTLS13 != 0 {
1778 if version < VersionTLS13 || candidate.flags&suiteTLS13 == 0 {
1779 continue
1780 }
1781 return candidate
David Benjamin5ecb88b2016-10-04 17:51:35 -04001782 }
1783 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
1784 continue
1785 }
1786 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
1787 continue
1788 }
1789 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
1790 continue
1791 }
David Benjamin5ecb88b2016-10-04 17:51:35 -04001792 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
1793 continue
David Benjamin83c0bc92014-08-04 01:23:53 -04001794 }
Adam Langley95c29f32014-06-20 12:00:00 -07001795 return candidate
1796 }
1797 }
1798
1799 return nil
1800}
David Benjaminf93995b2015-11-05 18:23:20 -05001801
1802func isTLS12Cipher(id uint16) bool {
1803 for _, cipher := range cipherSuites {
1804 if cipher.id != id {
1805 continue
1806 }
1807 return cipher.flags&suiteTLS12 != 0
1808 }
1809 // Unknown cipher.
1810 return false
1811}
David Benjamin65ac9972016-09-02 21:35:25 -04001812
1813func isGREASEValue(val uint16) bool {
David Benjamin3c6a1ea2016-09-26 18:30:05 -04001814 return val&0x0f0f == 0x0a0a && val&0xff == val>>8
David Benjamin65ac9972016-09-02 21:35:25 -04001815}