blob: abadf3ad97f55c139328fe8d020fe6e605dde44e [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)
David Benjamin7f78df42016-10-05 22:33:19 -0400472 if config.Bugs.SelectPSKIdentityOnResume != 0 {
473 hs.hello.pskIdentity = config.Bugs.SelectPSKIdentityOnResume
474 }
Steven Valdez803c77a2016-09-06 14:13:43 -0400475 c.didResume = true
476 break
Nick Harper728eed82016-07-07 17:36:52 -0700477 }
478
David Benjamin7f78df42016-10-05 22:33:19 -0400479 if config.Bugs.AlwaysSelectPSKIdentity {
480 hs.hello.hasPSKIdentity = true
481 hs.hello.pskIdentity = 0
482 }
483
Nick Harper0b3625b2016-07-25 16:16:28 -0700484 // If not resuming, select the cipher suite.
485 if hs.suite == nil {
486 var preferenceList, supportedList []uint16
487 if config.PreferServerCipherSuites {
488 preferenceList = config.cipherSuites()
489 supportedList = hs.clientHello.cipherSuites
490 } else {
491 preferenceList = hs.clientHello.cipherSuites
492 supportedList = config.cipherSuites()
493 }
494
495 for _, id := range preferenceList {
Steven Valdez803c77a2016-09-06 14:13:43 -0400496 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, true, true); hs.suite != nil {
Nick Harper0b3625b2016-07-25 16:16:28 -0700497 break
498 }
Nick Harper728eed82016-07-07 17:36:52 -0700499 }
500 }
501
502 if hs.suite == nil {
503 c.sendAlert(alertHandshakeFailure)
504 return errors.New("tls: no cipher suite supported by both client and server")
505 }
506
507 hs.hello.cipherSuite = hs.suite.id
Steven Valdez0ee2e112016-07-15 06:51:15 -0400508 if c.config.Bugs.SendCipherSuite != 0 {
509 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
510 }
511
Nick Harper728eed82016-07-07 17:36:52 -0700512 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
513 hs.finishedHash.discardHandshakeBuffer()
514 hs.writeClientHash(hs.clientHello.marshal())
515
Steven Valdez803c77a2016-09-06 14:13:43 -0400516 hs.hello.useCertAuth = hs.sessionState == nil
517
Nick Harper728eed82016-07-07 17:36:52 -0700518 // Resolve PSK and compute the early secret.
Nick Harper0b3625b2016-07-25 16:16:28 -0700519 var psk []byte
Steven Valdez803c77a2016-09-06 14:13:43 -0400520 if hs.sessionState != nil {
Nick Harper0b3625b2016-07-25 16:16:28 -0700521 psk = deriveResumptionPSK(hs.suite, hs.sessionState.masterSecret)
522 hs.finishedHash.setResumptionContext(deriveResumptionContext(hs.suite, hs.sessionState.masterSecret))
523 } else {
524 psk = hs.finishedHash.zeroSecret()
525 hs.finishedHash.setResumptionContext(hs.finishedHash.zeroSecret())
526 }
Nick Harper728eed82016-07-07 17:36:52 -0700527
528 earlySecret := hs.finishedHash.extractKey(hs.finishedHash.zeroSecret(), psk)
529
Steven Valdez803c77a2016-09-06 14:13:43 -0400530 if config.Bugs.OmitServerHelloSignatureAlgorithms {
531 hs.hello.useCertAuth = false
532 } else if config.Bugs.IncludeServerHelloSignatureAlgorithms {
533 hs.hello.useCertAuth = true
534 }
535
536 hs.hello.hasKeyShare = true
537 if hs.sessionState != nil && config.Bugs.NegotiatePSKResumption {
538 hs.hello.hasKeyShare = false
539 }
540 if config.Bugs.MissingKeyShare {
541 hs.hello.hasKeyShare = false
542 }
543
Nick Harper728eed82016-07-07 17:36:52 -0700544 // Resolve ECDHE and compute the handshake secret.
545 var ecdheSecret []byte
Steven Valdez803c77a2016-09-06 14:13:43 -0400546 if hs.hello.hasKeyShare {
Nick Harper728eed82016-07-07 17:36:52 -0700547 // Look for the key share corresponding to our selected curve.
548 var selectedKeyShare *keyShareEntry
549 for i := range hs.clientHello.keyShares {
550 if hs.clientHello.keyShares[i].group == selectedCurve {
551 selectedKeyShare = &hs.clientHello.keyShares[i]
552 break
553 }
554 }
555
David Benjamine73c7f42016-08-17 00:29:33 -0400556 if config.Bugs.ExpectMissingKeyShare && selectedKeyShare != nil {
557 return errors.New("tls: expected missing key share")
558 }
559
Steven Valdez5440fe02016-07-18 12:40:30 -0400560 sendHelloRetryRequest := selectedKeyShare == nil
561 if config.Bugs.UnnecessaryHelloRetryRequest {
562 sendHelloRetryRequest = true
563 }
564 if config.Bugs.SkipHelloRetryRequest {
565 sendHelloRetryRequest = false
566 }
567 if sendHelloRetryRequest {
568 firstTime := true
569 ResendHelloRetryRequest:
Nick Harperdcfbc672016-07-16 17:47:31 +0200570 // Send HelloRetryRequest.
571 helloRetryRequestMsg := helloRetryRequestMsg{
Steven Valdezfdd10992016-09-15 16:27:05 -0400572 vers: versionToWire(c.vers, c.isDTLS),
Nick Harperdcfbc672016-07-16 17:47:31 +0200573 cipherSuite: hs.hello.cipherSuite,
574 selectedGroup: selectedCurve,
575 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400576 if config.Bugs.SendHelloRetryRequestCurve != 0 {
577 helloRetryRequestMsg.selectedGroup = config.Bugs.SendHelloRetryRequestCurve
578 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200579 hs.writeServerHash(helloRetryRequestMsg.marshal())
580 c.writeRecord(recordTypeHandshake, helloRetryRequestMsg.marshal())
David Benjamine73c7f42016-08-17 00:29:33 -0400581 c.flushHandshake()
Nick Harperdcfbc672016-07-16 17:47:31 +0200582
583 // Read new ClientHello.
584 newMsg, err := c.readHandshake()
585 if err != nil {
586 return err
587 }
588 newClientHello, ok := newMsg.(*clientHelloMsg)
589 if !ok {
590 c.sendAlert(alertUnexpectedMessage)
591 return unexpectedMessageError(newClientHello, newMsg)
592 }
593 hs.writeClientHash(newClientHello.marshal())
594
595 // Check that the new ClientHello matches the old ClientHello, except for
596 // the addition of the new KeyShareEntry at the end of the list, and
597 // removing the EarlyDataIndication extension (if present).
598 newKeyShares := newClientHello.keyShares
599 if len(newKeyShares) == 0 || newKeyShares[len(newKeyShares)-1].group != selectedCurve {
600 return errors.New("tls: KeyShare from HelloRetryRequest not present in new ClientHello")
601 }
602 oldClientHelloCopy := *hs.clientHello
603 oldClientHelloCopy.raw = nil
604 oldClientHelloCopy.hasEarlyData = false
605 oldClientHelloCopy.earlyDataContext = nil
606 newClientHelloCopy := *newClientHello
607 newClientHelloCopy.raw = nil
608 newClientHelloCopy.keyShares = newKeyShares[:len(newKeyShares)-1]
609 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
610 return errors.New("tls: new ClientHello does not match")
611 }
612
Steven Valdez5440fe02016-07-18 12:40:30 -0400613 if firstTime && config.Bugs.SecondHelloRetryRequest {
614 firstTime = false
615 goto ResendHelloRetryRequest
616 }
617
Nick Harperdcfbc672016-07-16 17:47:31 +0200618 selectedKeyShare = &newKeyShares[len(newKeyShares)-1]
Nick Harper728eed82016-07-07 17:36:52 -0700619 }
620
621 // Once a curve has been selected and a key share identified,
622 // the server needs to generate a public value and send it in
623 // the ServerHello.
Steven Valdez5440fe02016-07-18 12:40:30 -0400624 curve, ok := curveForCurveID(selectedCurve)
Nick Harper728eed82016-07-07 17:36:52 -0700625 if !ok {
626 panic("tls: server failed to look up curve ID")
627 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400628 c.curveID = selectedCurve
629
630 var peerKey []byte
631 if config.Bugs.SkipHelloRetryRequest {
632 // If skipping HelloRetryRequest, use a random key to
633 // avoid crashing.
634 curve2, _ := curveForCurveID(selectedCurve)
635 var err error
636 peerKey, err = curve2.offer(config.rand())
637 if err != nil {
638 return err
639 }
640 } else {
641 peerKey = selectedKeyShare.keyExchange
642 }
643
Nick Harper728eed82016-07-07 17:36:52 -0700644 var publicKey []byte
645 var err error
Steven Valdez5440fe02016-07-18 12:40:30 -0400646 publicKey, ecdheSecret, err = curve.accept(config.rand(), peerKey)
Nick Harper728eed82016-07-07 17:36:52 -0700647 if err != nil {
648 c.sendAlert(alertHandshakeFailure)
649 return err
650 }
651 hs.hello.hasKeyShare = true
Steven Valdez0ee2e112016-07-15 06:51:15 -0400652
Steven Valdez5440fe02016-07-18 12:40:30 -0400653 curveID := selectedCurve
Steven Valdez0ee2e112016-07-15 06:51:15 -0400654 if c.config.Bugs.SendCurve != 0 {
655 curveID = config.Bugs.SendCurve
656 }
657 if c.config.Bugs.InvalidECDHPoint {
658 publicKey[0] ^= 0xff
659 }
660
Nick Harper728eed82016-07-07 17:36:52 -0700661 hs.hello.keyShare = keyShareEntry{
Steven Valdez0ee2e112016-07-15 06:51:15 -0400662 group: curveID,
Nick Harper728eed82016-07-07 17:36:52 -0700663 keyExchange: publicKey,
664 }
Steven Valdez143e8b32016-07-11 13:19:03 -0400665
666 if config.Bugs.EncryptedExtensionsWithKeyShare {
667 encryptedExtensions.extensions.hasKeyShare = true
668 encryptedExtensions.extensions.keyShare = keyShareEntry{
669 group: curveID,
670 keyExchange: publicKey,
671 }
672 }
Nick Harper728eed82016-07-07 17:36:52 -0700673 } else {
674 ecdheSecret = hs.finishedHash.zeroSecret()
675 }
676
677 // Send unencrypted ServerHello.
678 hs.writeServerHash(hs.hello.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400679 if config.Bugs.PartialEncryptedExtensionsWithServerHello {
680 helloBytes := hs.hello.marshal()
681 toWrite := make([]byte, 0, len(helloBytes)+1)
682 toWrite = append(toWrite, helloBytes...)
683 toWrite = append(toWrite, typeEncryptedExtensions)
684 c.writeRecord(recordTypeHandshake, toWrite)
685 } else {
686 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
687 }
Nick Harper728eed82016-07-07 17:36:52 -0700688 c.flushHandshake()
689
690 // Compute the handshake secret.
691 handshakeSecret := hs.finishedHash.extractKey(earlySecret, ecdheSecret)
692
693 // Switch to handshake traffic keys.
694 handshakeTrafficSecret := hs.finishedHash.deriveSecret(handshakeSecret, handshakeTrafficLabel)
David Benjamin21c00282016-07-18 21:56:23 +0200695 c.out.useTrafficSecret(c.vers, hs.suite, handshakeTrafficSecret, handshakePhase, serverWrite)
696 c.in.useTrafficSecret(c.vers, hs.suite, handshakeTrafficSecret, handshakePhase, clientWrite)
Nick Harper728eed82016-07-07 17:36:52 -0700697
Steven Valdez803c77a2016-09-06 14:13:43 -0400698 if hs.hello.useCertAuth {
David Benjamin615119a2016-07-06 19:22:55 -0700699 if hs.clientHello.ocspStapling {
700 encryptedExtensions.extensions.ocspResponse = hs.cert.OCSPStaple
701 }
702 if hs.clientHello.sctListSupported {
703 encryptedExtensions.extensions.sctList = hs.cert.SignedCertificateTimestampList
704 }
David Benjamindaa88502016-10-04 16:32:16 -0400705 } else {
706 if config.Bugs.SendOCSPResponseOnResume != nil {
707 encryptedExtensions.extensions.ocspResponse = config.Bugs.SendOCSPResponseOnResume
708 }
709 if config.Bugs.SendSCTListOnResume != nil {
710 encryptedExtensions.extensions.sctList = config.Bugs.SendSCTListOnResume
711 }
David Benjamin615119a2016-07-06 19:22:55 -0700712 }
713
Nick Harper728eed82016-07-07 17:36:52 -0700714 // Send EncryptedExtensions.
715 hs.writeServerHash(encryptedExtensions.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400716 if config.Bugs.PartialEncryptedExtensionsWithServerHello {
717 // The first byte has already been sent.
718 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()[1:])
719 } else {
720 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal())
721 }
Nick Harper728eed82016-07-07 17:36:52 -0700722
Steven Valdez803c77a2016-09-06 14:13:43 -0400723 if hs.hello.useCertAuth {
Nick Harper728eed82016-07-07 17:36:52 -0700724 if config.ClientAuth >= RequestClientCert {
David Benjamin8d343b42016-07-09 14:26:01 -0700725 // Request a client certificate
726 certReq := &certificateRequestMsg{
727 hasSignatureAlgorithm: true,
728 hasRequestContext: true,
David Benjamin8a8349b2016-08-18 02:32:23 -0400729 requestContext: config.Bugs.SendRequestContext,
David Benjamin8d343b42016-07-09 14:26:01 -0700730 }
731 if !config.Bugs.NoSignatureAlgorithms {
David Benjaminf74ec792016-07-13 21:18:49 -0400732 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin8d343b42016-07-09 14:26:01 -0700733 }
734
735 // An empty list of certificateAuthorities signals to
736 // the client that it may send any certificate in response
737 // to our request. When we know the CAs we trust, then
738 // we can send them down, so that the client can choose
739 // an appropriate certificate to give to us.
740 if config.ClientCAs != nil {
741 certReq.certificateAuthorities = config.ClientCAs.Subjects()
742 }
743 hs.writeServerHash(certReq.marshal())
744 c.writeRecord(recordTypeHandshake, certReq.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700745 }
746
747 certMsg := &certificateMsg{
748 hasRequestContext: true,
749 }
750 if !config.Bugs.EmptyCertificateList {
751 certMsg.certificates = hs.cert.Certificate
752 }
David Benjamin1edae6b2016-07-13 16:58:23 -0400753 certMsgBytes := certMsg.marshal()
David Benjamin1edae6b2016-07-13 16:58:23 -0400754 hs.writeServerHash(certMsgBytes)
755 c.writeRecord(recordTypeHandshake, certMsgBytes)
Nick Harper728eed82016-07-07 17:36:52 -0700756
757 certVerify := &certificateVerifyMsg{
758 hasSignatureAlgorithm: true,
759 }
760
761 // Determine the hash to sign.
762 privKey := hs.cert.PrivateKey
763
764 var err error
765 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, config, hs.clientHello.signatureAlgorithms)
766 if err != nil {
767 c.sendAlert(alertInternalError)
768 return err
769 }
770
771 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
772 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
773 if err != nil {
774 c.sendAlert(alertInternalError)
775 return err
776 }
777
Steven Valdez0ee2e112016-07-15 06:51:15 -0400778 if config.Bugs.SendSignatureAlgorithm != 0 {
779 certVerify.signatureAlgorithm = config.Bugs.SendSignatureAlgorithm
780 }
781
Nick Harper728eed82016-07-07 17:36:52 -0700782 hs.writeServerHash(certVerify.marshal())
783 c.writeRecord(recordTypeHandshake, certVerify.marshal())
Steven Valdez803c77a2016-09-06 14:13:43 -0400784 } else if hs.sessionState != nil {
Nick Harper0b3625b2016-07-25 16:16:28 -0700785 // Pick up certificates from the session instead.
David Benjamin5ecb88b2016-10-04 17:51:35 -0400786 if len(hs.sessionState.certificates) > 0 {
Nick Harper0b3625b2016-07-25 16:16:28 -0700787 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
788 return err
789 }
790 }
Nick Harper728eed82016-07-07 17:36:52 -0700791 }
792
793 finished := new(finishedMsg)
794 finished.verifyData = hs.finishedHash.serverSum(handshakeTrafficSecret)
795 if config.Bugs.BadFinished {
796 finished.verifyData[0]++
797 }
798 hs.writeServerHash(finished.marshal())
799 c.writeRecord(recordTypeHandshake, finished.marshal())
David Benjamin02edcd02016-07-27 17:40:37 -0400800 if c.config.Bugs.SendExtraFinished {
801 c.writeRecord(recordTypeHandshake, finished.marshal())
802 }
Nick Harper728eed82016-07-07 17:36:52 -0700803 c.flushHandshake()
804
805 // The various secrets do not incorporate the client's final leg, so
806 // derive them now before updating the handshake context.
807 masterSecret := hs.finishedHash.extractKey(handshakeSecret, hs.finishedHash.zeroSecret())
808 trafficSecret := hs.finishedHash.deriveSecret(masterSecret, applicationTrafficLabel)
809
David Benjamin2aad4062016-07-14 23:15:40 -0400810 // Switch to application data keys on write. In particular, any alerts
811 // from the client certificate are sent over these keys.
David Benjamin21c00282016-07-18 21:56:23 +0200812 c.out.useTrafficSecret(c.vers, hs.suite, trafficSecret, applicationPhase, serverWrite)
David Benjamin2aad4062016-07-14 23:15:40 -0400813
Nick Harper728eed82016-07-07 17:36:52 -0700814 // If we requested a client certificate, then the client must send a
815 // certificate message, even if it's empty.
816 if config.ClientAuth >= RequestClientCert {
David Benjamin8d343b42016-07-09 14:26:01 -0700817 msg, err := c.readHandshake()
818 if err != nil {
819 return err
820 }
821
822 certMsg, ok := msg.(*certificateMsg)
823 if !ok {
824 c.sendAlert(alertUnexpectedMessage)
825 return unexpectedMessageError(certMsg, msg)
826 }
827 hs.writeClientHash(certMsg.marshal())
828
829 if len(certMsg.certificates) == 0 {
830 // The client didn't actually send a certificate
831 switch config.ClientAuth {
832 case RequireAnyClientCert, RequireAndVerifyClientCert:
David Benjamin1db9e1b2016-10-07 20:51:43 -0400833 c.sendAlert(alertCertificateRequired)
David Benjamin8d343b42016-07-09 14:26:01 -0700834 return errors.New("tls: client didn't provide a certificate")
835 }
836 }
837
838 pub, err := hs.processCertsFromClient(certMsg.certificates)
839 if err != nil {
840 return err
841 }
842
843 if len(c.peerCertificates) > 0 {
844 msg, err = c.readHandshake()
845 if err != nil {
846 return err
847 }
848
849 certVerify, ok := msg.(*certificateVerifyMsg)
850 if !ok {
851 c.sendAlert(alertUnexpectedMessage)
852 return unexpectedMessageError(certVerify, msg)
853 }
854
David Benjaminf74ec792016-07-13 21:18:49 -0400855 c.peerSignatureAlgorithm = certVerify.signatureAlgorithm
David Benjamin8d343b42016-07-09 14:26:01 -0700856 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
857 if err := verifyMessage(c.vers, pub, config, certVerify.signatureAlgorithm, input, certVerify.signature); err != nil {
858 c.sendAlert(alertBadCertificate)
859 return err
860 }
861 hs.writeClientHash(certVerify.marshal())
862 }
Nick Harper728eed82016-07-07 17:36:52 -0700863 }
864
865 // Read the client Finished message.
866 msg, err := c.readHandshake()
867 if err != nil {
868 return err
869 }
870 clientFinished, ok := msg.(*finishedMsg)
871 if !ok {
872 c.sendAlert(alertUnexpectedMessage)
873 return unexpectedMessageError(clientFinished, msg)
874 }
875
876 verify := hs.finishedHash.clientSum(handshakeTrafficSecret)
877 if len(verify) != len(clientFinished.verifyData) ||
878 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
879 c.sendAlert(alertHandshakeFailure)
880 return errors.New("tls: client's Finished message was incorrect")
881 }
David Benjamin97a0a082016-07-13 17:57:35 -0400882 hs.writeClientHash(clientFinished.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700883
David Benjamin2aad4062016-07-14 23:15:40 -0400884 // Switch to application data keys on read.
David Benjamin21c00282016-07-18 21:56:23 +0200885 c.in.useTrafficSecret(c.vers, hs.suite, trafficSecret, applicationPhase, clientWrite)
Nick Harper728eed82016-07-07 17:36:52 -0700886
Nick Harper728eed82016-07-07 17:36:52 -0700887 c.cipherSuite = hs.suite
David Benjamin97a0a082016-07-13 17:57:35 -0400888 c.exporterSecret = hs.finishedHash.deriveSecret(masterSecret, exporterLabel)
David Benjamin58104882016-07-18 01:25:41 +0200889 c.resumptionSecret = hs.finishedHash.deriveSecret(masterSecret, resumptionLabel)
890
891 // TODO(davidben): Allow configuring the number of tickets sent for
892 // testing.
893 if !c.config.SessionTicketsDisabled {
894 ticketCount := 2
895 for i := 0; i < ticketCount; i++ {
896 c.SendNewSessionTicket()
897 }
898 }
Nick Harper728eed82016-07-07 17:36:52 -0700899 return nil
900}
901
David Benjaminf25dda92016-07-04 10:05:26 -0700902// processClientHello processes the ClientHello message from the client and
903// decides whether we will perform session resumption.
904func (hs *serverHandshakeState) processClientHello() (isResume bool, err error) {
905 config := hs.c.config
906 c := hs.c
907
908 hs.hello = &serverHelloMsg{
909 isDTLS: c.isDTLS,
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400910 vers: versionToWire(c.vers, c.isDTLS),
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400911 versOverride: config.Bugs.SendServerHelloVersion,
David Benjaminf25dda92016-07-04 10:05:26 -0700912 compressionMethod: compressionNone,
913 }
914
915 hs.hello.random = make([]byte, 32)
916 _, err = io.ReadFull(config.rand(), hs.hello.random)
917 if err != nil {
918 c.sendAlert(alertInternalError)
919 return false, err
920 }
David Benjamin1f61f0d2016-07-10 12:20:35 -0400921 // Signal downgrades in the server random, per draft-ietf-tls-tls13-14,
922 // section 6.3.1.2.
Nick Harper85f20c22016-07-04 10:11:59 -0700923 if c.vers <= VersionTLS12 && config.maxVersion(c.isDTLS) >= VersionTLS13 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400924 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS13)
Nick Harper85f20c22016-07-04 10:11:59 -0700925 }
926 if c.vers <= VersionTLS11 && config.maxVersion(c.isDTLS) == VersionTLS12 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400927 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS12)
Nick Harper85f20c22016-07-04 10:11:59 -0700928 }
David Benjaminf25dda92016-07-04 10:05:26 -0700929
930 foundCompression := false
931 // We only support null compression, so check that the client offered it.
932 for _, compression := range hs.clientHello.compressionMethods {
933 if compression == compressionNone {
934 foundCompression = true
935 break
936 }
937 }
938
939 if !foundCompression {
940 c.sendAlert(alertHandshakeFailure)
941 return false, errors.New("tls: client does not support uncompressed connections")
942 }
David Benjamin7d79f832016-07-04 09:20:45 -0700943
944 if err := hs.processClientExtensions(&hs.hello.extensions); err != nil {
945 return false, err
Adam Langley09505632015-07-30 18:10:13 -0700946 }
Adam Langley95c29f32014-06-20 12:00:00 -0700947
948 supportedCurve := false
949 preferredCurves := config.curvePreferences()
950Curves:
951 for _, curve := range hs.clientHello.supportedCurves {
952 for _, supported := range preferredCurves {
953 if supported == curve {
954 supportedCurve = true
955 break Curves
956 }
957 }
958 }
959
960 supportedPointFormat := false
961 for _, pointFormat := range hs.clientHello.supportedPoints {
962 if pointFormat == pointFormatUncompressed {
963 supportedPointFormat = true
964 break
965 }
966 }
967 hs.ellipticOk = supportedCurve && supportedPointFormat
968
Adam Langley95c29f32014-06-20 12:00:00 -0700969 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
970
David Benjamin4b27d9f2015-05-12 22:42:52 -0400971 // For test purposes, check that the peer never offers a session when
972 // renegotiating.
973 if c.cipherSuite != nil && len(hs.clientHello.sessionId) > 0 && c.config.Bugs.FailIfResumeOnRenego {
974 return false, errors.New("tls: offered resumption on renegotiation")
975 }
976
David Benjamindd6fed92015-10-23 17:41:12 -0400977 if c.config.Bugs.FailIfSessionOffered && (len(hs.clientHello.sessionTicket) > 0 || len(hs.clientHello.sessionId) > 0) {
978 return false, errors.New("tls: client offered a session ticket or ID")
979 }
980
Adam Langley95c29f32014-06-20 12:00:00 -0700981 if hs.checkForResumption() {
982 return true, nil
983 }
984
Adam Langley95c29f32014-06-20 12:00:00 -0700985 var preferenceList, supportedList []uint16
986 if c.config.PreferServerCipherSuites {
987 preferenceList = c.config.cipherSuites()
988 supportedList = hs.clientHello.cipherSuites
989 } else {
990 preferenceList = hs.clientHello.cipherSuites
991 supportedList = c.config.cipherSuites()
992 }
993
994 for _, id := range preferenceList {
Steven Valdez803c77a2016-09-06 14:13:43 -0400995 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700996 break
997 }
998 }
999
1000 if hs.suite == nil {
1001 c.sendAlert(alertHandshakeFailure)
1002 return false, errors.New("tls: no cipher suite supported by both client and server")
1003 }
1004
1005 return false, nil
1006}
1007
David Benjamin7d79f832016-07-04 09:20:45 -07001008// processClientExtensions processes all ClientHello extensions not directly
1009// related to cipher suite negotiation and writes responses in serverExtensions.
1010func (hs *serverHandshakeState) processClientExtensions(serverExtensions *serverExtensions) error {
1011 config := hs.c.config
1012 c := hs.c
1013
David Benjamin8d315d72016-07-18 01:03:18 +02001014 if c.vers < VersionTLS13 || config.Bugs.NegotiateRenegotiationInfoAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -07001015 if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) {
1016 c.sendAlert(alertHandshakeFailure)
1017 return errors.New("tls: renegotiation mismatch")
David Benjamin7d79f832016-07-04 09:20:45 -07001018 }
David Benjamin7d79f832016-07-04 09:20:45 -07001019
Nick Harper728eed82016-07-07 17:36:52 -07001020 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
1021 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.clientVerify...)
1022 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.serverVerify...)
1023 if c.config.Bugs.BadRenegotiationInfo {
1024 serverExtensions.secureRenegotiation[0] ^= 0x80
1025 }
1026 } else {
1027 serverExtensions.secureRenegotiation = hs.clientHello.secureRenegotiation
1028 }
1029
1030 if c.noRenegotiationInfo() {
1031 serverExtensions.secureRenegotiation = nil
1032 }
David Benjamin7d79f832016-07-04 09:20:45 -07001033 }
1034
1035 serverExtensions.duplicateExtension = c.config.Bugs.DuplicateExtension
1036
1037 if len(hs.clientHello.serverName) > 0 {
1038 c.serverName = hs.clientHello.serverName
1039 }
1040 if len(config.Certificates) == 0 {
1041 c.sendAlert(alertInternalError)
1042 return errors.New("tls: no certificates configured")
1043 }
1044 hs.cert = &config.Certificates[0]
1045 if len(hs.clientHello.serverName) > 0 {
1046 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
1047 }
1048 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
1049 return errors.New("tls: unexpected server name")
1050 }
1051
1052 if len(hs.clientHello.alpnProtocols) > 0 {
1053 if proto := c.config.Bugs.ALPNProtocol; proto != nil {
1054 serverExtensions.alpnProtocol = *proto
1055 serverExtensions.alpnProtocolEmpty = len(*proto) == 0
1056 c.clientProtocol = *proto
1057 c.usedALPN = true
1058 } else if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
1059 serverExtensions.alpnProtocol = selectedProto
1060 c.clientProtocol = selectedProto
1061 c.usedALPN = true
1062 }
1063 }
Nick Harper728eed82016-07-07 17:36:52 -07001064
David Benjamin0c40a962016-08-01 12:05:50 -04001065 if len(c.config.Bugs.SendALPN) > 0 {
1066 serverExtensions.alpnProtocol = c.config.Bugs.SendALPN
1067 }
1068
David Benjamin8d315d72016-07-18 01:03:18 +02001069 if c.vers < VersionTLS13 || config.Bugs.NegotiateNPNAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -07001070 if len(hs.clientHello.alpnProtocols) == 0 || c.config.Bugs.NegotiateALPNAndNPN {
1071 // Although sending an empty NPN extension is reasonable, Firefox has
1072 // had a bug around this. Best to send nothing at all if
1073 // config.NextProtos is empty. See
1074 // https://code.google.com/p/go/issues/detail?id=5445.
1075 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
1076 serverExtensions.nextProtoNeg = true
1077 serverExtensions.nextProtos = config.NextProtos
1078 serverExtensions.npnLast = config.Bugs.SwapNPNAndALPN
1079 }
David Benjamin7d79f832016-07-04 09:20:45 -07001080 }
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.NegotiateEMSAtAllVersions {
David Benjamin163c9562016-08-29 23:14:17 -04001084 disableEMS := config.Bugs.NoExtendedMasterSecret
1085 if c.cipherSuite != nil {
1086 disableEMS = config.Bugs.NoExtendedMasterSecretOnRenegotiation
1087 }
1088 serverExtensions.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !disableEMS
Steven Valdez143e8b32016-07-11 13:19:03 -04001089 }
David Benjamin7d79f832016-07-04 09:20:45 -07001090
David Benjamin8d315d72016-07-18 01:03:18 +02001091 if c.vers < VersionTLS13 || config.Bugs.NegotiateChannelIDAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -07001092 if hs.clientHello.channelIDSupported && config.RequestChannelID {
1093 serverExtensions.channelIDRequested = true
1094 }
David Benjamin7d79f832016-07-04 09:20:45 -07001095 }
1096
1097 if hs.clientHello.srtpProtectionProfiles != nil {
1098 SRTPLoop:
1099 for _, p1 := range c.config.SRTPProtectionProfiles {
1100 for _, p2 := range hs.clientHello.srtpProtectionProfiles {
1101 if p1 == p2 {
1102 serverExtensions.srtpProtectionProfile = p1
1103 c.srtpProtectionProfile = p1
1104 break SRTPLoop
1105 }
1106 }
1107 }
1108 }
1109
1110 if c.config.Bugs.SendSRTPProtectionProfile != 0 {
1111 serverExtensions.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
1112 }
1113
1114 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
1115 if hs.clientHello.customExtension != *expected {
1116 return fmt.Errorf("tls: bad custom extension contents %q", hs.clientHello.customExtension)
1117 }
1118 }
1119 serverExtensions.customExtension = config.Bugs.CustomExtension
1120
Steven Valdez143e8b32016-07-11 13:19:03 -04001121 if c.config.Bugs.AdvertiseTicketExtension {
1122 serverExtensions.ticketSupported = true
1123 }
1124
David Benjamin65ac9972016-09-02 21:35:25 -04001125 if !hs.clientHello.hasGREASEExtension && config.Bugs.ExpectGREASE {
1126 return errors.New("tls: no GREASE extension found")
1127 }
1128
David Benjamin7d79f832016-07-04 09:20:45 -07001129 return nil
1130}
1131
Adam Langley95c29f32014-06-20 12:00:00 -07001132// checkForResumption returns true if we should perform resumption on this connection.
1133func (hs *serverHandshakeState) checkForResumption() bool {
1134 c := hs.c
1135
David Benjamin405da482016-08-08 17:25:07 -04001136 ticket := hs.clientHello.sessionTicket
1137 if len(ticket) == 0 && len(hs.clientHello.pskIdentities) > 0 && c.config.Bugs.AcceptAnySession {
Steven Valdez5b986082016-09-01 12:29:49 -04001138 ticket = hs.clientHello.pskIdentities[0].ticket
David Benjamin405da482016-08-08 17:25:07 -04001139 }
1140 if len(ticket) > 0 {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001141 if c.config.SessionTicketsDisabled {
1142 return false
1143 }
David Benjaminb0c8db72014-09-24 15:19:56 -04001144
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001145 var ok bool
David Benjamin405da482016-08-08 17:25:07 -04001146 if hs.sessionState, ok = c.decryptTicket(ticket); !ok {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001147 return false
1148 }
1149 } else {
1150 if c.config.ServerSessionCache == nil {
1151 return false
1152 }
1153
1154 var ok bool
1155 sessionId := string(hs.clientHello.sessionId)
1156 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
1157 return false
1158 }
Adam Langley95c29f32014-06-20 12:00:00 -07001159 }
1160
Steven Valdez803c77a2016-09-06 14:13:43 -04001161 if c.config.Bugs.AcceptAnySession {
1162 // Replace the cipher suite with one known to work, to test
1163 // cross-version resumption attempts.
1164 hs.sessionState.cipherSuite = TLS_RSA_WITH_AES_128_CBC_SHA
1165 } else {
David Benjamin405da482016-08-08 17:25:07 -04001166 // Never resume a session for a different SSL version.
1167 if c.vers != hs.sessionState.vers {
1168 return false
Adam Langley95c29f32014-06-20 12:00:00 -07001169 }
David Benjamin405da482016-08-08 17:25:07 -04001170
1171 cipherSuiteOk := false
1172 // Check that the client is still offering the ciphersuite in the session.
1173 for _, id := range hs.clientHello.cipherSuites {
1174 if id == hs.sessionState.cipherSuite {
1175 cipherSuiteOk = true
1176 break
1177 }
1178 }
1179 if !cipherSuiteOk {
1180 return false
1181 }
Adam Langley95c29f32014-06-20 12:00:00 -07001182 }
1183
1184 // Check that we also support the ciphersuite from the session.
Steven Valdez803c77a2016-09-06 14:13:43 -04001185 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), c.vers, hs.ellipticOk, hs.ecdsaOk)
1186
Adam Langley95c29f32014-06-20 12:00:00 -07001187 if hs.suite == nil {
1188 return false
1189 }
1190
1191 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
1192 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
1193 if needClientCerts && !sessionHasClientCerts {
1194 return false
1195 }
1196 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
1197 return false
1198 }
1199
1200 return true
1201}
1202
1203func (hs *serverHandshakeState) doResumeHandshake() error {
1204 c := hs.c
1205
1206 hs.hello.cipherSuite = hs.suite.id
David Benjaminece3de92015-03-16 18:02:20 -04001207 if c.config.Bugs.SendCipherSuite != 0 {
1208 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
1209 }
Adam Langley95c29f32014-06-20 12:00:00 -07001210 // We echo the client's session ID in the ServerHello to let it know
1211 // that we're doing a resumption.
1212 hs.hello.sessionId = hs.clientHello.sessionId
Nick Harperb3d51be2016-07-01 11:43:18 -04001213 hs.hello.extensions.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -07001214
David Benjamin80d1b352016-05-04 19:19:06 -04001215 if c.config.Bugs.SendSCTListOnResume != nil {
Nick Harperb3d51be2016-07-01 11:43:18 -04001216 hs.hello.extensions.sctList = c.config.Bugs.SendSCTListOnResume
David Benjamin80d1b352016-05-04 19:19:06 -04001217 }
1218
David Benjamindaa88502016-10-04 16:32:16 -04001219 if c.config.Bugs.SendOCSPResponseOnResume != nil {
1220 // There is no way, syntactically, to send an OCSP response on a
1221 // resumption handshake.
1222 hs.hello.extensions.ocspStapling = true
1223 }
1224
Adam Langley95c29f32014-06-20 12:00:00 -07001225 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -04001226 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -04001227 hs.writeClientHash(hs.clientHello.marshal())
1228 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001229
1230 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
1231
1232 if len(hs.sessionState.certificates) > 0 {
1233 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
1234 return err
1235 }
1236 }
1237
1238 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -07001239 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -07001240
1241 return nil
1242}
1243
1244func (hs *serverHandshakeState) doFullHandshake() error {
1245 config := hs.c.config
1246 c := hs.c
1247
David Benjamin48cae082014-10-27 01:06:24 -04001248 isPSK := hs.suite.flags&suitePSK != 0
1249 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001250 hs.hello.extensions.ocspStapling = true
Adam Langley95c29f32014-06-20 12:00:00 -07001251 }
1252
David Benjamin61f95272014-11-25 01:55:35 -05001253 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001254 hs.hello.extensions.sctList = hs.cert.SignedCertificateTimestampList
David Benjamin61f95272014-11-25 01:55:35 -05001255 }
1256
Nick Harperb3d51be2016-07-01 11:43:18 -04001257 hs.hello.extensions.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
Adam Langley95c29f32014-06-20 12:00:00 -07001258 hs.hello.cipherSuite = hs.suite.id
David Benjamin6095de82014-12-27 01:50:38 -05001259 if config.Bugs.SendCipherSuite != 0 {
1260 hs.hello.cipherSuite = config.Bugs.SendCipherSuite
1261 }
Nick Harperb3d51be2016-07-01 11:43:18 -04001262 c.extendedMasterSecret = hs.hello.extensions.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -07001263
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001264 // Generate a session ID if we're to save the session.
Nick Harperb3d51be2016-07-01 11:43:18 -04001265 if !hs.hello.extensions.ticketSupported && config.ServerSessionCache != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001266 hs.hello.sessionId = make([]byte, 32)
1267 if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
1268 c.sendAlert(alertInternalError)
1269 return errors.New("tls: short read from Rand: " + err.Error())
1270 }
1271 }
1272
Adam Langley95c29f32014-06-20 12:00:00 -07001273 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -04001274 hs.writeClientHash(hs.clientHello.marshal())
1275 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001276
David Benjaminabe94e32016-09-04 14:18:58 -04001277 if config.Bugs.SendSNIWarningAlert {
1278 c.SendAlert(alertLevelWarning, alertUnrecognizedName)
1279 }
1280
Adam Langley95c29f32014-06-20 12:00:00 -07001281 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
1282
David Benjamin48cae082014-10-27 01:06:24 -04001283 if !isPSK {
1284 certMsg := new(certificateMsg)
David Benjamin8923c0b2015-06-07 11:42:34 -04001285 if !config.Bugs.EmptyCertificateList {
1286 certMsg.certificates = hs.cert.Certificate
1287 }
David Benjamin48cae082014-10-27 01:06:24 -04001288 if !config.Bugs.UnauthenticatedECDH {
David Benjaminbcb2d912015-02-24 23:45:43 -05001289 certMsgBytes := certMsg.marshal()
David Benjaminbcb2d912015-02-24 23:45:43 -05001290 hs.writeServerHash(certMsgBytes)
1291 c.writeRecord(recordTypeHandshake, certMsgBytes)
David Benjamin48cae082014-10-27 01:06:24 -04001292 }
David Benjamin1c375dd2014-07-12 00:48:23 -04001293 }
Adam Langley95c29f32014-06-20 12:00:00 -07001294
Nick Harperb3d51be2016-07-01 11:43:18 -04001295 if hs.hello.extensions.ocspStapling && !c.config.Bugs.SkipCertificateStatus {
Adam Langley95c29f32014-06-20 12:00:00 -07001296 certStatus := new(certificateStatusMsg)
1297 certStatus.statusType = statusTypeOCSP
1298 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -04001299 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001300 c.writeRecord(recordTypeHandshake, certStatus.marshal())
1301 }
1302
1303 keyAgreement := hs.suite.ka(c.vers)
1304 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
1305 if err != nil {
1306 c.sendAlert(alertHandshakeFailure)
1307 return err
1308 }
Steven Valdez5440fe02016-07-18 12:40:30 -04001309 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
1310 c.curveID = ecdhe.curveID
1311 }
David Benjamin9c651c92014-07-12 13:27:45 -04001312 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -04001313 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001314 c.writeRecord(recordTypeHandshake, skx.marshal())
1315 }
1316
1317 if config.ClientAuth >= RequestClientCert {
1318 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -04001319 certReq := &certificateRequestMsg{
1320 certificateTypes: config.ClientCertificateTypes,
1321 }
1322 if certReq.certificateTypes == nil {
1323 certReq.certificateTypes = []byte{
1324 byte(CertTypeRSASign),
1325 byte(CertTypeECDSASign),
1326 }
Adam Langley95c29f32014-06-20 12:00:00 -07001327 }
1328 if c.vers >= VersionTLS12 {
Nick Harper60edffd2016-06-21 15:19:24 -07001329 certReq.hasSignatureAlgorithm = true
1330 if !config.Bugs.NoSignatureAlgorithms {
David Benjamin7a41d372016-07-09 11:21:54 -07001331 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin000800a2014-11-14 01:43:59 -05001332 }
Adam Langley95c29f32014-06-20 12:00:00 -07001333 }
1334
1335 // An empty list of certificateAuthorities signals to
1336 // the client that it may send any certificate in response
1337 // to our request. When we know the CAs we trust, then
1338 // we can send them down, so that the client can choose
1339 // an appropriate certificate to give to us.
1340 if config.ClientCAs != nil {
1341 certReq.certificateAuthorities = config.ClientCAs.Subjects()
1342 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001343 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001344 c.writeRecord(recordTypeHandshake, certReq.marshal())
1345 }
1346
1347 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001348 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001349 c.writeRecord(recordTypeHandshake, helloDone.marshal())
David Benjamin582ba042016-07-07 12:33:25 -07001350 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001351
1352 var pub crypto.PublicKey // public key for client auth, if any
1353
David Benjamin83f90402015-01-27 01:09:43 -05001354 if err := c.simulatePacketLoss(nil); err != nil {
1355 return err
1356 }
Adam Langley95c29f32014-06-20 12:00:00 -07001357 msg, err := c.readHandshake()
1358 if err != nil {
1359 return err
1360 }
1361
1362 var ok bool
1363 // If we requested a client certificate, then the client must send a
1364 // certificate message, even if it's empty.
1365 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -04001366 var certMsg *certificateMsg
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001367 var certificates [][]byte
1368 if certMsg, ok = msg.(*certificateMsg); ok {
1369 if c.vers == VersionSSL30 && len(certMsg.certificates) == 0 {
1370 return errors.New("tls: empty certificate message in SSL 3.0")
1371 }
1372
1373 hs.writeClientHash(certMsg.marshal())
1374 certificates = certMsg.certificates
1375 } else if c.vers != VersionSSL30 {
1376 // In TLS, the Certificate message is required. In SSL
1377 // 3.0, the peer skips it when sending no certificates.
Adam Langley95c29f32014-06-20 12:00:00 -07001378 c.sendAlert(alertUnexpectedMessage)
1379 return unexpectedMessageError(certMsg, msg)
1380 }
Adam Langley95c29f32014-06-20 12:00:00 -07001381
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001382 if len(certificates) == 0 {
Adam Langley95c29f32014-06-20 12:00:00 -07001383 // The client didn't actually send a certificate
1384 switch config.ClientAuth {
1385 case RequireAnyClientCert, RequireAndVerifyClientCert:
1386 c.sendAlert(alertBadCertificate)
1387 return errors.New("tls: client didn't provide a certificate")
1388 }
1389 }
1390
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001391 pub, err = hs.processCertsFromClient(certificates)
Adam Langley95c29f32014-06-20 12:00:00 -07001392 if err != nil {
1393 return err
1394 }
1395
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001396 if ok {
1397 msg, err = c.readHandshake()
1398 if err != nil {
1399 return err
1400 }
Adam Langley95c29f32014-06-20 12:00:00 -07001401 }
1402 }
1403
1404 // Get client key exchange
1405 ckx, ok := msg.(*clientKeyExchangeMsg)
1406 if !ok {
1407 c.sendAlert(alertUnexpectedMessage)
1408 return unexpectedMessageError(ckx, msg)
1409 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001410 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001411
David Benjamine098ec22014-08-27 23:13:20 -04001412 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
1413 if err != nil {
1414 c.sendAlert(alertHandshakeFailure)
1415 return err
1416 }
Adam Langley75712922014-10-10 16:23:43 -07001417 if c.extendedMasterSecret {
1418 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1419 } else {
1420 if c.config.Bugs.RequireExtendedMasterSecret {
1421 return errors.New("tls: extended master secret required but not supported by peer")
1422 }
1423 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
1424 }
David Benjamine098ec22014-08-27 23:13:20 -04001425
Adam Langley95c29f32014-06-20 12:00:00 -07001426 // If we received a client cert in response to our certificate request message,
1427 // the client will send us a certificateVerifyMsg immediately after the
1428 // clientKeyExchangeMsg. This message is a digest of all preceding
1429 // handshake-layer messages that is signed using the private key corresponding
1430 // to the client's certificate. This allows us to verify that the client is in
1431 // possession of the private key of the certificate.
1432 if len(c.peerCertificates) > 0 {
1433 msg, err = c.readHandshake()
1434 if err != nil {
1435 return err
1436 }
1437 certVerify, ok := msg.(*certificateVerifyMsg)
1438 if !ok {
1439 c.sendAlert(alertUnexpectedMessage)
1440 return unexpectedMessageError(certVerify, msg)
1441 }
1442
David Benjaminde620d92014-07-18 15:03:41 -04001443 // Determine the signature type.
Nick Harper60edffd2016-06-21 15:19:24 -07001444 var sigAlg signatureAlgorithm
1445 if certVerify.hasSignatureAlgorithm {
1446 sigAlg = certVerify.signatureAlgorithm
Nick Harper60edffd2016-06-21 15:19:24 -07001447 c.peerSignatureAlgorithm = sigAlg
David Benjaminde620d92014-07-18 15:03:41 -04001448 }
1449
Nick Harper60edffd2016-06-21 15:19:24 -07001450 if c.vers > VersionSSL30 {
David Benjamin1fb125c2016-07-08 18:52:12 -07001451 err = verifyMessage(c.vers, pub, c.config, sigAlg, hs.finishedHash.buffer, certVerify.signature)
Nick Harper60edffd2016-06-21 15:19:24 -07001452 } else {
1453 // SSL 3.0's client certificate construction is
1454 // incompatible with signatureAlgorithm.
1455 rsaPub, ok := pub.(*rsa.PublicKey)
1456 if !ok {
1457 err = errors.New("unsupported key type for client certificate")
1458 } else {
1459 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
1460 err = rsa.VerifyPKCS1v15(rsaPub, crypto.MD5SHA1, digest, certVerify.signature)
David Benjaminde620d92014-07-18 15:03:41 -04001461 }
Adam Langley95c29f32014-06-20 12:00:00 -07001462 }
1463 if err != nil {
1464 c.sendAlert(alertBadCertificate)
1465 return errors.New("could not validate signature of connection nonces: " + err.Error())
1466 }
1467
David Benjamin83c0bc92014-08-04 01:23:53 -04001468 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001469 }
1470
David Benjamine098ec22014-08-27 23:13:20 -04001471 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001472
1473 return nil
1474}
1475
1476func (hs *serverHandshakeState) establishKeys() error {
1477 c := hs.c
1478
1479 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001480 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 -07001481
1482 var clientCipher, serverCipher interface{}
1483 var clientHash, serverHash macFunction
1484
1485 if hs.suite.aead == nil {
1486 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
1487 clientHash = hs.suite.mac(c.vers, clientMAC)
1488 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
1489 serverHash = hs.suite.mac(c.vers, serverMAC)
1490 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001491 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1492 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001493 }
1494
1495 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
1496 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
1497
1498 return nil
1499}
1500
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001501func (hs *serverHandshakeState) readFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001502 c := hs.c
1503
1504 c.readRecord(recordTypeChangeCipherSpec)
1505 if err := c.in.error(); err != nil {
1506 return err
1507 }
1508
Nick Harperb3d51be2016-07-01 11:43:18 -04001509 if hs.hello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001510 msg, err := c.readHandshake()
1511 if err != nil {
1512 return err
1513 }
1514 nextProto, ok := msg.(*nextProtoMsg)
1515 if !ok {
1516 c.sendAlert(alertUnexpectedMessage)
1517 return unexpectedMessageError(nextProto, msg)
1518 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001519 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001520 c.clientProtocol = nextProto.proto
1521 }
1522
Nick Harperb3d51be2016-07-01 11:43:18 -04001523 if hs.hello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001524 msg, err := c.readHandshake()
1525 if err != nil {
1526 return err
1527 }
David Benjamin24599a82016-06-30 18:56:53 -04001528 channelIDMsg, ok := msg.(*channelIDMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001529 if !ok {
1530 c.sendAlert(alertUnexpectedMessage)
David Benjamin24599a82016-06-30 18:56:53 -04001531 return unexpectedMessageError(channelIDMsg, msg)
David Benjamind30a9902014-08-24 01:44:23 -04001532 }
David Benjamin24599a82016-06-30 18:56:53 -04001533 x := new(big.Int).SetBytes(channelIDMsg.channelID[0:32])
1534 y := new(big.Int).SetBytes(channelIDMsg.channelID[32:64])
1535 r := new(big.Int).SetBytes(channelIDMsg.channelID[64:96])
1536 s := new(big.Int).SetBytes(channelIDMsg.channelID[96:128])
David Benjamind30a9902014-08-24 01:44:23 -04001537 if !elliptic.P256().IsOnCurve(x, y) {
1538 return errors.New("tls: invalid channel ID public key")
1539 }
1540 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
1541 var resumeHash []byte
1542 if isResume {
1543 resumeHash = hs.sessionState.handshakeHash
1544 }
1545 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
1546 return errors.New("tls: invalid channel ID signature")
1547 }
1548 c.channelID = channelID
1549
David Benjamin24599a82016-06-30 18:56:53 -04001550 hs.writeClientHash(channelIDMsg.marshal())
David Benjamind30a9902014-08-24 01:44:23 -04001551 }
1552
Adam Langley95c29f32014-06-20 12:00:00 -07001553 msg, err := c.readHandshake()
1554 if err != nil {
1555 return err
1556 }
1557 clientFinished, ok := msg.(*finishedMsg)
1558 if !ok {
1559 c.sendAlert(alertUnexpectedMessage)
1560 return unexpectedMessageError(clientFinished, msg)
1561 }
1562
1563 verify := hs.finishedHash.clientSum(hs.masterSecret)
1564 if len(verify) != len(clientFinished.verifyData) ||
1565 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
1566 c.sendAlert(alertHandshakeFailure)
1567 return errors.New("tls: client's Finished message is incorrect")
1568 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001569 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001570 copy(out, clientFinished.verifyData)
Adam Langley95c29f32014-06-20 12:00:00 -07001571
David Benjamin83c0bc92014-08-04 01:23:53 -04001572 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001573 return nil
1574}
1575
1576func (hs *serverHandshakeState) sendSessionTicket() error {
Adam Langley95c29f32014-06-20 12:00:00 -07001577 c := hs.c
Adam Langley95c29f32014-06-20 12:00:00 -07001578 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -04001579 vers: c.vers,
1580 cipherSuite: hs.suite.id,
1581 masterSecret: hs.masterSecret,
1582 certificates: hs.certsFromClient,
1583 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -07001584 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001585
Nick Harperb3d51be2016-07-01 11:43:18 -04001586 if !hs.hello.extensions.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001587 if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
1588 c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
1589 }
1590 return nil
1591 }
1592
1593 m := new(newSessionTicketMsg)
1594
David Benjamindd6fed92015-10-23 17:41:12 -04001595 if !c.config.Bugs.SendEmptySessionTicket {
1596 var err error
1597 m.ticket, err = c.encryptTicket(&state)
1598 if err != nil {
1599 return err
1600 }
Adam Langley95c29f32014-06-20 12:00:00 -07001601 }
Adam Langley95c29f32014-06-20 12:00:00 -07001602
David Benjamin83c0bc92014-08-04 01:23:53 -04001603 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001604 c.writeRecord(recordTypeHandshake, m.marshal())
1605
1606 return nil
1607}
1608
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001609func (hs *serverHandshakeState) sendFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001610 c := hs.c
1611
David Benjamin86271ee2014-07-21 16:14:03 -04001612 finished := new(finishedMsg)
1613 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001614 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001615 if c.config.Bugs.BadFinished {
1616 finished.verifyData[0]++
1617 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001618 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001619 hs.finishedBytes = finished.marshal()
1620 hs.writeServerHash(hs.finishedBytes)
1621 postCCSBytes := hs.finishedBytes
David Benjamin86271ee2014-07-21 16:14:03 -04001622
1623 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
1624 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
1625 postCCSBytes = postCCSBytes[5:]
David Benjamin61672812016-07-14 23:10:43 -04001626 } else if c.config.Bugs.SendUnencryptedFinished {
1627 c.writeRecord(recordTypeHandshake, postCCSBytes)
1628 postCCSBytes = nil
David Benjamin86271ee2014-07-21 16:14:03 -04001629 }
David Benjamin582ba042016-07-07 12:33:25 -07001630 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001631
David Benjamina0e52232014-07-19 17:39:58 -04001632 if !c.config.Bugs.SkipChangeCipherSpec {
David Benjamin8411b242015-11-26 12:07:28 -05001633 ccs := []byte{1}
1634 if c.config.Bugs.BadChangeCipherSpec != nil {
1635 ccs = c.config.Bugs.BadChangeCipherSpec
1636 }
1637 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamina0e52232014-07-19 17:39:58 -04001638 }
Adam Langley95c29f32014-06-20 12:00:00 -07001639
David Benjamin4189bd92015-01-25 23:52:39 -05001640 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1641 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1642 }
David Benjamindc3da932015-03-12 15:09:02 -04001643 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1644 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1645 return errors.New("tls: simulating post-CCS alert")
1646 }
David Benjamin4189bd92015-01-25 23:52:39 -05001647
David Benjamin61672812016-07-14 23:10:43 -04001648 if !c.config.Bugs.SkipFinished && len(postCCSBytes) > 0 {
David Benjaminb80168e2015-02-08 18:30:14 -05001649 c.writeRecord(recordTypeHandshake, postCCSBytes)
David Benjamin02edcd02016-07-27 17:40:37 -04001650 if c.config.Bugs.SendExtraFinished {
1651 c.writeRecord(recordTypeHandshake, finished.marshal())
1652 }
1653
David Benjamin12d2c482016-07-24 10:56:51 -04001654 if !c.config.Bugs.PackHelloRequestWithFinished {
1655 // Defer flushing until renegotiation.
1656 c.flushHandshake()
1657 }
David Benjaminb3774b92015-01-31 17:16:01 -05001658 }
Adam Langley95c29f32014-06-20 12:00:00 -07001659
David Benjaminc565ebb2015-04-03 04:06:36 -04001660 c.cipherSuite = hs.suite
Adam Langley95c29f32014-06-20 12:00:00 -07001661
1662 return nil
1663}
1664
1665// processCertsFromClient takes a chain of client certificates either from a
1666// Certificates message or from a sessionState and verifies them. It returns
1667// the public key of the leaf certificate.
1668func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
1669 c := hs.c
1670
1671 hs.certsFromClient = certificates
1672 certs := make([]*x509.Certificate, len(certificates))
1673 var err error
1674 for i, asn1Data := range certificates {
1675 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
1676 c.sendAlert(alertBadCertificate)
1677 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
1678 }
1679 }
1680
1681 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
1682 opts := x509.VerifyOptions{
1683 Roots: c.config.ClientCAs,
1684 CurrentTime: c.config.time(),
1685 Intermediates: x509.NewCertPool(),
1686 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
1687 }
1688
1689 for _, cert := range certs[1:] {
1690 opts.Intermediates.AddCert(cert)
1691 }
1692
1693 chains, err := certs[0].Verify(opts)
1694 if err != nil {
1695 c.sendAlert(alertBadCertificate)
1696 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
1697 }
1698
1699 ok := false
1700 for _, ku := range certs[0].ExtKeyUsage {
1701 if ku == x509.ExtKeyUsageClientAuth {
1702 ok = true
1703 break
1704 }
1705 }
1706 if !ok {
1707 c.sendAlert(alertHandshakeFailure)
1708 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
1709 }
1710
1711 c.verifiedChains = chains
1712 }
1713
1714 if len(certs) > 0 {
1715 var pub crypto.PublicKey
1716 switch key := certs[0].PublicKey.(type) {
1717 case *ecdsa.PublicKey, *rsa.PublicKey:
1718 pub = key
1719 default:
1720 c.sendAlert(alertUnsupportedCertificate)
1721 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
1722 }
1723 c.peerCertificates = certs
1724 return pub, nil
1725 }
1726
1727 return nil, nil
1728}
1729
David Benjamin83c0bc92014-08-04 01:23:53 -04001730func (hs *serverHandshakeState) writeServerHash(msg []byte) {
1731 // writeServerHash is called before writeRecord.
1732 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1733}
1734
1735func (hs *serverHandshakeState) writeClientHash(msg []byte) {
1736 // writeClientHash is called after readHandshake.
1737 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1738}
1739
1740func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
1741 if hs.c.isDTLS {
1742 // This is somewhat hacky. DTLS hashes a slightly different format.
1743 // First, the TLS header.
1744 hs.finishedHash.Write(msg[:4])
1745 // Then the sequence number and reassembled fragment offset (always 0).
1746 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1747 // Then the reassembled fragment (always equal to the message length).
1748 hs.finishedHash.Write(msg[1:4])
1749 // And then the message body.
1750 hs.finishedHash.Write(msg[4:])
1751 } else {
1752 hs.finishedHash.Write(msg)
1753 }
1754}
1755
Adam Langley95c29f32014-06-20 12:00:00 -07001756// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
1757// is acceptable to use.
Steven Valdez803c77a2016-09-06 14:13:43 -04001758func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
Adam Langley95c29f32014-06-20 12:00:00 -07001759 for _, supported := range supportedCipherSuites {
1760 if id == supported {
1761 var candidate *cipherSuite
1762
1763 for _, s := range cipherSuites {
1764 if s.id == id {
1765 candidate = s
1766 break
1767 }
1768 }
1769 if candidate == nil {
1770 continue
1771 }
Steven Valdez803c77a2016-09-06 14:13:43 -04001772
Adam Langley95c29f32014-06-20 12:00:00 -07001773 // Don't select a ciphersuite which we can't
1774 // support for this client.
Steven Valdez803c77a2016-09-06 14:13:43 -04001775 if version >= VersionTLS13 || candidate.flags&suiteTLS13 != 0 {
1776 if version < VersionTLS13 || candidate.flags&suiteTLS13 == 0 {
1777 continue
1778 }
1779 return candidate
David Benjamin5ecb88b2016-10-04 17:51:35 -04001780 }
1781 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
1782 continue
1783 }
1784 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
1785 continue
1786 }
1787 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
1788 continue
1789 }
David Benjamin5ecb88b2016-10-04 17:51:35 -04001790 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
1791 continue
David Benjamin83c0bc92014-08-04 01:23:53 -04001792 }
Adam Langley95c29f32014-06-20 12:00:00 -07001793 return candidate
1794 }
1795 }
1796
1797 return nil
1798}
David Benjaminf93995b2015-11-05 18:23:20 -05001799
1800func isTLS12Cipher(id uint16) bool {
1801 for _, cipher := range cipherSuites {
1802 if cipher.id != id {
1803 continue
1804 }
1805 return cipher.flags&suiteTLS12 != 0
1806 }
1807 // Unknown cipher.
1808 return false
1809}
David Benjamin65ac9972016-09-02 21:35:25 -04001810
1811func isGREASEValue(val uint16) bool {
David Benjamin3c6a1ea2016-09-26 18:30:05 -04001812 return val&0x0f0f == 0x0a0a && val&0xff == val>>8
David Benjamin65ac9972016-09-02 21:35:25 -04001813}