blob: a9b2ff189fe5b4fb5b4e20f96058cce856429045 [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"
Steven Valdeza833c352016-11-01 13:39:36 -040019 "time"
Adam Langley95c29f32014-06-20 12:00:00 -070020)
21
22// serverHandshakeState contains details of a server handshake in progress.
23// It's discarded once the handshake has completed.
24type serverHandshakeState struct {
25 c *Conn
26 clientHello *clientHelloMsg
27 hello *serverHelloMsg
28 suite *cipherSuite
29 ellipticOk bool
30 ecdsaOk bool
31 sessionState *sessionState
32 finishedHash finishedHash
33 masterSecret []byte
34 certsFromClient [][]byte
35 cert *Certificate
David Benjamin83f90402015-01-27 01:09:43 -050036 finishedBytes []byte
Adam Langley95c29f32014-06-20 12:00:00 -070037}
38
39// serverHandshake performs a TLS handshake as a server.
40func (c *Conn) serverHandshake() error {
41 config := c.config
42
43 // If this is the first server handshake, we generate a random key to
44 // encrypt the tickets with.
45 config.serverInitOnce.Do(config.serverInit)
46
David Benjamin83c0bc92014-08-04 01:23:53 -040047 c.sendHandshakeSeq = 0
48 c.recvHandshakeSeq = 0
49
Adam Langley95c29f32014-06-20 12:00:00 -070050 hs := serverHandshakeState{
51 c: c,
52 }
David Benjaminf25dda92016-07-04 10:05:26 -070053 if err := hs.readClientHello(); err != nil {
54 return err
55 }
Adam Langley95c29f32014-06-20 12:00:00 -070056
David Benjamin8d315d72016-07-18 01:03:18 +020057 if c.vers >= VersionTLS13 {
Nick Harper728eed82016-07-07 17:36:52 -070058 if err := hs.doTLS13Handshake(); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -070059 return err
60 }
Nick Harper728eed82016-07-07 17:36:52 -070061 } else {
62 isResume, err := hs.processClientHello()
63 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -070064 return err
65 }
Nick Harper728eed82016-07-07 17:36:52 -070066
67 // For an overview of TLS handshaking, see https://tools.ietf.org/html/rfc5246#section-7.3
68 if isResume {
69 // The client has included a session ticket and so we do an abbreviated handshake.
70 if err := hs.doResumeHandshake(); err != nil {
71 return err
72 }
73 if err := hs.establishKeys(); err != nil {
74 return err
75 }
76 if c.config.Bugs.RenewTicketOnResume {
77 if err := hs.sendSessionTicket(); err != nil {
78 return err
79 }
80 }
81 if err := hs.sendFinished(c.firstFinished[:]); err != nil {
82 return err
83 }
84 // Most retransmits are triggered by a timeout, but the final
85 // leg of the handshake is retransmited upon re-receiving a
86 // Finished.
87 if err := c.simulatePacketLoss(func() {
David Benjamin02edcd02016-07-27 17:40:37 -040088 c.sendHandshakeSeq--
Nick Harper728eed82016-07-07 17:36:52 -070089 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
90 c.flushHandshake()
91 }); err != nil {
92 return err
93 }
94 if err := hs.readFinished(nil, isResume); err != nil {
95 return err
96 }
97 c.didResume = true
98 } else {
99 // The client didn't include a session ticket, or it wasn't
100 // valid so we do a full handshake.
101 if err := hs.doFullHandshake(); err != nil {
102 return err
103 }
104 if err := hs.establishKeys(); err != nil {
105 return err
106 }
107 if err := hs.readFinished(c.firstFinished[:], isResume); err != nil {
108 return err
109 }
110 if c.config.Bugs.AlertBeforeFalseStartTest != 0 {
111 c.sendAlert(c.config.Bugs.AlertBeforeFalseStartTest)
112 }
113 if c.config.Bugs.ExpectFalseStart {
114 if err := c.readRecord(recordTypeApplicationData); err != nil {
115 return fmt.Errorf("tls: peer did not false start: %s", err)
116 }
117 }
David Benjaminbed9aae2014-08-07 19:13:38 -0400118 if err := hs.sendSessionTicket(); err != nil {
119 return err
120 }
Nick Harper728eed82016-07-07 17:36:52 -0700121 if err := hs.sendFinished(nil); err != nil {
122 return err
David Benjamine58c4f52014-08-24 03:47:07 -0400123 }
124 }
David Benjamin97a0a082016-07-13 17:57:35 -0400125
126 c.exporterSecret = hs.masterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700127 }
128 c.handshakeComplete = true
David Benjaminc565ebb2015-04-03 04:06:36 -0400129 copy(c.clientRandom[:], hs.clientHello.random)
130 copy(c.serverRandom[:], hs.hello.random)
Adam Langley95c29f32014-06-20 12:00:00 -0700131
132 return nil
133}
134
David Benjaminf25dda92016-07-04 10:05:26 -0700135// readClientHello reads a ClientHello message from the client and determines
136// the protocol version.
137func (hs *serverHandshakeState) readClientHello() error {
Adam Langley95c29f32014-06-20 12:00:00 -0700138 config := hs.c.config
139 c := hs.c
140
David Benjamin83f90402015-01-27 01:09:43 -0500141 if err := c.simulatePacketLoss(nil); err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700142 return err
David Benjamin83f90402015-01-27 01:09:43 -0500143 }
Adam Langley95c29f32014-06-20 12:00:00 -0700144 msg, err := c.readHandshake()
145 if err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700146 return err
Adam Langley95c29f32014-06-20 12:00:00 -0700147 }
148 var ok bool
149 hs.clientHello, ok = msg.(*clientHelloMsg)
150 if !ok {
151 c.sendAlert(alertUnexpectedMessage)
David Benjaminf25dda92016-07-04 10:05:26 -0700152 return unexpectedMessageError(hs.clientHello, msg)
Adam Langley95c29f32014-06-20 12:00:00 -0700153 }
Adam Langley33ad2b52015-07-20 17:43:53 -0700154 if size := config.Bugs.RequireClientHelloSize; size != 0 && len(hs.clientHello.raw) != size {
David Benjaminf25dda92016-07-04 10:05:26 -0700155 return fmt.Errorf("tls: ClientHello record size is %d, but expected %d", len(hs.clientHello.raw), size)
Feng Lu41aa3252014-11-21 22:47:56 -0800156 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400157
158 if c.isDTLS && !config.Bugs.SkipHelloVerifyRequest {
David Benjamin8bc38f52014-08-16 12:07:27 -0400159 // Per RFC 6347, the version field in HelloVerifyRequest SHOULD
160 // be always DTLS 1.0
David Benjamin83c0bc92014-08-04 01:23:53 -0400161 helloVerifyRequest := &helloVerifyRequestMsg{
David Benjaminda4789e2016-10-31 19:23:34 -0400162 vers: versionToWire(VersionTLS10, c.isDTLS),
David Benjamin83c0bc92014-08-04 01:23:53 -0400163 cookie: make([]byte, 32),
164 }
165 if _, err := io.ReadFull(c.config.rand(), helloVerifyRequest.cookie); err != nil {
166 c.sendAlert(alertInternalError)
David Benjaminf25dda92016-07-04 10:05:26 -0700167 return errors.New("dtls: short read from Rand: " + err.Error())
David Benjamin83c0bc92014-08-04 01:23:53 -0400168 }
169 c.writeRecord(recordTypeHandshake, helloVerifyRequest.marshal())
David Benjamin582ba042016-07-07 12:33:25 -0700170 c.flushHandshake()
David Benjamin83c0bc92014-08-04 01:23:53 -0400171
David Benjamin83f90402015-01-27 01:09:43 -0500172 if err := c.simulatePacketLoss(nil); err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700173 return err
David Benjamin83f90402015-01-27 01:09:43 -0500174 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400175 msg, err := c.readHandshake()
176 if err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700177 return err
David Benjamin83c0bc92014-08-04 01:23:53 -0400178 }
179 newClientHello, ok := msg.(*clientHelloMsg)
180 if !ok {
181 c.sendAlert(alertUnexpectedMessage)
David Benjaminf25dda92016-07-04 10:05:26 -0700182 return unexpectedMessageError(hs.clientHello, msg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400183 }
184 if !bytes.Equal(newClientHello.cookie, helloVerifyRequest.cookie) {
David Benjaminf25dda92016-07-04 10:05:26 -0700185 return errors.New("dtls: invalid cookie")
David Benjamin83c0bc92014-08-04 01:23:53 -0400186 }
David Benjaminf2fedef2014-08-16 01:37:34 -0400187
188 // Apart from the cookie, the two ClientHellos must
189 // match. Note that clientHello.equal compares the
190 // serialization, so we make a copy.
191 oldClientHelloCopy := *hs.clientHello
192 oldClientHelloCopy.raw = nil
193 oldClientHelloCopy.cookie = nil
194 newClientHelloCopy := *newClientHello
195 newClientHelloCopy.raw = nil
196 newClientHelloCopy.cookie = nil
197 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
David Benjaminf25dda92016-07-04 10:05:26 -0700198 return errors.New("dtls: retransmitted ClientHello does not match")
David Benjamin83c0bc92014-08-04 01:23:53 -0400199 }
200 hs.clientHello = newClientHello
201 }
202
David Benjaminc44b1df2014-11-23 12:11:01 -0500203 if config.Bugs.RequireSameRenegoClientVersion && c.clientVersion != 0 {
204 if c.clientVersion != hs.clientHello.vers {
David Benjaminf25dda92016-07-04 10:05:26 -0700205 return fmt.Errorf("tls: client offered different version on renego")
David Benjaminc44b1df2014-11-23 12:11:01 -0500206 }
207 }
Steven Valdezfdd10992016-09-15 16:27:05 -0400208
David Benjaminc44b1df2014-11-23 12:11:01 -0500209 c.clientVersion = hs.clientHello.vers
Steven Valdezfdd10992016-09-15 16:27:05 -0400210
211 // Convert the ClientHello wire version to a protocol version.
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400212 var clientVersion uint16
213 if c.isDTLS {
214 if hs.clientHello.vers <= 0xfefd {
215 clientVersion = VersionTLS12
216 } else if hs.clientHello.vers <= 0xfeff {
217 clientVersion = VersionTLS10
218 }
219 } else {
Steven Valdezfdd10992016-09-15 16:27:05 -0400220 if hs.clientHello.vers >= VersionTLS12 {
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400221 clientVersion = VersionTLS12
222 } else if hs.clientHello.vers >= VersionTLS11 {
223 clientVersion = VersionTLS11
224 } else if hs.clientHello.vers >= VersionTLS10 {
225 clientVersion = VersionTLS10
226 } else if hs.clientHello.vers >= VersionSSL30 {
227 clientVersion = VersionSSL30
228 }
229 }
230
231 if config.Bugs.NegotiateVersion != 0 {
232 c.vers = config.Bugs.NegotiateVersion
233 } else if c.haveVers && config.Bugs.NegotiateVersionOnRenego != 0 {
234 c.vers = config.Bugs.NegotiateVersionOnRenego
Steven Valdezfdd10992016-09-15 16:27:05 -0400235 } else if len(hs.clientHello.supportedVersions) > 0 {
236 // Use the versions extension if supplied.
David Benjamind9791bf2016-09-27 16:39:52 -0400237 var foundVersion, foundGREASE bool
Steven Valdezfdd10992016-09-15 16:27:05 -0400238 for _, extVersion := range hs.clientHello.supportedVersions {
David Benjamind9791bf2016-09-27 16:39:52 -0400239 if isGREASEValue(extVersion) {
240 foundGREASE = true
241 }
Steven Valdezfdd10992016-09-15 16:27:05 -0400242 extVersion, ok = wireToVersion(extVersion, c.isDTLS)
243 if !ok {
244 continue
245 }
David Benjamind9791bf2016-09-27 16:39:52 -0400246 if config.isSupportedVersion(extVersion, c.isDTLS) && !foundVersion {
Steven Valdezfdd10992016-09-15 16:27:05 -0400247 c.vers = extVersion
248 foundVersion = true
249 break
250 }
251 }
252 if !foundVersion {
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400253 c.sendAlert(alertProtocolVersion)
Steven Valdezfdd10992016-09-15 16:27:05 -0400254 return errors.New("tls: client did not offer any supported protocol versions")
255 }
David Benjamind9791bf2016-09-27 16:39:52 -0400256 if config.Bugs.ExpectGREASE && !foundGREASE {
257 return errors.New("tls: no GREASE version value found")
258 }
Steven Valdezfdd10992016-09-15 16:27:05 -0400259 } else {
260 // Otherwise, use the legacy ClientHello version.
261 version := clientVersion
262 if maxVersion := config.maxVersion(c.isDTLS); version > maxVersion {
263 version = maxVersion
264 }
265 if version == 0 || !config.isSupportedVersion(version, c.isDTLS) {
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400266 return fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
267 }
Steven Valdezfdd10992016-09-15 16:27:05 -0400268 c.vers = version
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400269 }
270 c.haveVers = true
David Benjaminc44b1df2014-11-23 12:11:01 -0500271
David Benjamin6ae7f072015-01-26 10:22:13 -0500272 // Reject < 1.2 ClientHellos with signature_algorithms.
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400273 if clientVersion < VersionTLS12 && len(hs.clientHello.signatureAlgorithms) > 0 {
David Benjaminf25dda92016-07-04 10:05:26 -0700274 return fmt.Errorf("tls: client included signature_algorithms before TLS 1.2")
David Benjamin72dc7832015-03-16 17:49:43 -0400275 }
David Benjamin6ae7f072015-01-26 10:22:13 -0500276
David Benjaminf93995b2015-11-05 18:23:20 -0500277 // Check the client cipher list is consistent with the version.
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400278 if clientVersion < VersionTLS12 {
David Benjaminf93995b2015-11-05 18:23:20 -0500279 for _, id := range hs.clientHello.cipherSuites {
280 if isTLS12Cipher(id) {
David Benjaminf25dda92016-07-04 10:05:26 -0700281 return fmt.Errorf("tls: client offered TLS 1.2 cipher before TLS 1.2")
David Benjaminf93995b2015-11-05 18:23:20 -0500282 }
283 }
284 }
285
David Benjamin405da482016-08-08 17:25:07 -0400286 if config.Bugs.ExpectNoTLS12Session {
287 if len(hs.clientHello.sessionId) > 0 {
288 return fmt.Errorf("tls: client offered an unexpected session ID")
289 }
290 if len(hs.clientHello.sessionTicket) > 0 {
291 return fmt.Errorf("tls: client offered an unexpected session ticket")
292 }
293 }
294
295 if config.Bugs.ExpectNoTLS13PSK && len(hs.clientHello.pskIdentities) > 0 {
296 return fmt.Errorf("tls: client offered unexpected PSK identities")
297 }
298
David Benjamin65ac9972016-09-02 21:35:25 -0400299 var scsvFound, greaseFound bool
David Benjaminf25dda92016-07-04 10:05:26 -0700300 for _, cipherSuite := range hs.clientHello.cipherSuites {
301 if cipherSuite == fallbackSCSV {
302 scsvFound = true
David Benjamin65ac9972016-09-02 21:35:25 -0400303 }
304 if isGREASEValue(cipherSuite) {
305 greaseFound = true
David Benjaminf25dda92016-07-04 10:05:26 -0700306 }
307 }
308
309 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
310 return errors.New("tls: no fallback SCSV found when expected")
311 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
312 return errors.New("tls: fallback SCSV found when not expected")
313 }
314
David Benjamin65ac9972016-09-02 21:35:25 -0400315 if !greaseFound && config.Bugs.ExpectGREASE {
316 return errors.New("tls: no GREASE cipher suite value found")
317 }
318
319 greaseFound = false
320 for _, curve := range hs.clientHello.supportedCurves {
321 if isGREASEValue(uint16(curve)) {
322 greaseFound = true
323 break
324 }
325 }
326
327 if !greaseFound && config.Bugs.ExpectGREASE {
328 return errors.New("tls: no GREASE curve value found")
329 }
330
331 if len(hs.clientHello.keyShares) > 0 {
332 greaseFound = false
333 for _, keyShare := range hs.clientHello.keyShares {
334 if isGREASEValue(uint16(keyShare.group)) {
335 greaseFound = true
336 break
337 }
338 }
339
340 if !greaseFound && config.Bugs.ExpectGREASE {
341 return errors.New("tls: no GREASE curve value found")
342 }
343 }
344
David Benjaminf25dda92016-07-04 10:05:26 -0700345 if config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
David Benjamin7a41d372016-07-09 11:21:54 -0700346 hs.clientHello.signatureAlgorithms = config.signSignatureAlgorithms()
David Benjaminf25dda92016-07-04 10:05:26 -0700347 }
348 if config.Bugs.IgnorePeerCurvePreferences {
349 hs.clientHello.supportedCurves = config.curvePreferences()
350 }
351 if config.Bugs.IgnorePeerCipherPreferences {
352 hs.clientHello.cipherSuites = config.cipherSuites()
353 }
354
355 return nil
356}
357
Nick Harper728eed82016-07-07 17:36:52 -0700358func (hs *serverHandshakeState) doTLS13Handshake() error {
359 c := hs.c
360 config := c.config
361
362 hs.hello = &serverHelloMsg{
David Benjamin490469f2016-10-05 22:44:38 -0400363 isDTLS: c.isDTLS,
364 vers: versionToWire(c.vers, c.isDTLS),
365 versOverride: config.Bugs.SendServerHelloVersion,
366 customExtension: config.Bugs.CustomUnencryptedExtension,
367 unencryptedALPN: config.Bugs.SendUnencryptedALPN,
Steven Valdez5440fe02016-07-18 12:40:30 -0400368 }
369
Nick Harper728eed82016-07-07 17:36:52 -0700370 hs.hello.random = make([]byte, 32)
371 if _, err := io.ReadFull(config.rand(), hs.hello.random); err != nil {
372 c.sendAlert(alertInternalError)
373 return err
374 }
375
376 // TLS 1.3 forbids clients from advertising any non-null compression.
377 if len(hs.clientHello.compressionMethods) != 1 || hs.clientHello.compressionMethods[0] != compressionNone {
378 return errors.New("tls: client sent compression method other than null for TLS 1.3")
379 }
380
381 // Prepare an EncryptedExtensions message, but do not send it yet.
382 encryptedExtensions := new(encryptedExtensionsMsg)
Steven Valdez143e8b32016-07-11 13:19:03 -0400383 encryptedExtensions.empty = config.Bugs.EmptyEncryptedExtensions
Nick Harper728eed82016-07-07 17:36:52 -0700384 if err := hs.processClientExtensions(&encryptedExtensions.extensions); err != nil {
385 return err
386 }
387
388 supportedCurve := false
389 var selectedCurve CurveID
390 preferredCurves := config.curvePreferences()
391Curves:
392 for _, curve := range hs.clientHello.supportedCurves {
393 for _, supported := range preferredCurves {
394 if supported == curve {
395 supportedCurve = true
396 selectedCurve = curve
397 break Curves
398 }
399 }
400 }
401
Steven Valdez803c77a2016-09-06 14:13:43 -0400402 if !supportedCurve {
403 c.sendAlert(alertHandshakeFailure)
404 return errors.New("tls: no curve supported by both client and server")
405 }
Nick Harper728eed82016-07-07 17:36:52 -0700406
David Benjamin405da482016-08-08 17:25:07 -0400407 pskIdentities := hs.clientHello.pskIdentities
Steven Valdeza833c352016-11-01 13:39:36 -0400408 pskKEModes := hs.clientHello.pskKEModes
409
David Benjamin405da482016-08-08 17:25:07 -0400410 if len(pskIdentities) == 0 && len(hs.clientHello.sessionTicket) > 0 && c.config.Bugs.AcceptAnySession {
Steven Valdez5b986082016-09-01 12:29:49 -0400411 psk := pskIdentity{
Steven Valdeza833c352016-11-01 13:39:36 -0400412 ticket: hs.clientHello.sessionTicket,
Steven Valdez5b986082016-09-01 12:29:49 -0400413 }
414 pskIdentities = []pskIdentity{psk}
Steven Valdeza833c352016-11-01 13:39:36 -0400415 pskKEModes = []byte{pskDHEKEMode}
David Benjamin405da482016-08-08 17:25:07 -0400416 }
Steven Valdez5b986082016-09-01 12:29:49 -0400417
Steven Valdeza833c352016-11-01 13:39:36 -0400418 var pskIndex int
419 foundKEMode := bytes.IndexByte(pskKEModes, pskDHEKEMode) >= 0
420 if foundKEMode {
421 for i, pskIdentity := range pskIdentities {
422 // TODO(svaldez): Check the obfuscatedTicketAge before accepting 0-RTT.
423 sessionState, ok := c.decryptTicket(pskIdentity.ticket)
424 if !ok {
David Benjamin405da482016-08-08 17:25:07 -0400425 continue
426 }
David Benjamin405da482016-08-08 17:25:07 -0400427
Steven Valdeza833c352016-11-01 13:39:36 -0400428 if config.Bugs.AcceptAnySession {
429 // Replace the cipher suite with one known to work, to
430 // test cross-version resumption attempts.
431 sessionState.cipherSuite = TLS_AES_128_GCM_SHA256
432 } else {
David Benjamin0b8f85e2016-11-16 11:45:34 +0900433 if sessionState.vers != c.vers {
Steven Valdeza833c352016-11-01 13:39:36 -0400434 continue
Steven Valdez803c77a2016-09-06 14:13:43 -0400435 }
Steven Valdeza833c352016-11-01 13:39:36 -0400436 if sessionState.ticketExpiration.Before(c.config.time()) {
437 continue
438 }
439
440 clientTicketAge := time.Duration(uint32(pskIdentity.obfuscatedTicketAge-sessionState.ticketAgeAdd)) * time.Millisecond
441 if config.Bugs.ExpectTicketAge != 0 && clientTicketAge != config.Bugs.ExpectTicketAge {
442 c.sendAlert(alertHandshakeFailure)
443 return errors.New("tls: invalid ticket age")
444 }
445
446 cipherSuiteOk := false
447 // Check that the client is still offering the ciphersuite in the session.
448 for _, id := range hs.clientHello.cipherSuites {
449 if id == sessionState.cipherSuite {
450 cipherSuiteOk = true
451 break
452 }
453 }
454 if !cipherSuiteOk {
455 continue
456 }
457
Steven Valdez803c77a2016-09-06 14:13:43 -0400458 }
Steven Valdeza833c352016-11-01 13:39:36 -0400459
460 // Check that we also support the ciphersuite from the session.
461 suite := c.tryCipherSuite(sessionState.cipherSuite, c.config.cipherSuites(), c.vers, true, true)
462 if suite == nil {
Steven Valdez803c77a2016-09-06 14:13:43 -0400463 continue
Nick Harper0b3625b2016-07-25 16:16:28 -0700464 }
David Benjamin405da482016-08-08 17:25:07 -0400465
Steven Valdeza833c352016-11-01 13:39:36 -0400466 hs.sessionState = sessionState
467 hs.suite = suite
468 hs.hello.hasPSKIdentity = true
469 hs.hello.pskIdentity = uint16(i)
470 pskIndex = i
471 if config.Bugs.SelectPSKIdentityOnResume != 0 {
472 hs.hello.pskIdentity = config.Bugs.SelectPSKIdentityOnResume
473 }
474 c.didResume = true
475 break
Nick Harper0b3625b2016-07-25 16:16:28 -0700476 }
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
Steven Valdeza833c352016-11-01 13:39:36 -0400484 // Verify the PSK binder. Note there may not be a PSK binder if
485 // AcceptAnyBinder is set. See https://crbug.com/boringssl/115.
486 if hs.sessionState != nil && !config.Bugs.AcceptAnySession {
487 binderToVerify := hs.clientHello.pskBinders[pskIndex]
488 if err := verifyPSKBinder(hs.clientHello, hs.sessionState, binderToVerify, []byte{}); err != nil {
489 return err
490 }
491 }
492
Nick Harper0b3625b2016-07-25 16:16:28 -0700493 // If not resuming, select the cipher suite.
494 if hs.suite == nil {
495 var preferenceList, supportedList []uint16
496 if config.PreferServerCipherSuites {
497 preferenceList = config.cipherSuites()
498 supportedList = hs.clientHello.cipherSuites
499 } else {
500 preferenceList = hs.clientHello.cipherSuites
501 supportedList = config.cipherSuites()
502 }
503
504 for _, id := range preferenceList {
Steven Valdez803c77a2016-09-06 14:13:43 -0400505 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, true, true); hs.suite != nil {
Nick Harper0b3625b2016-07-25 16:16:28 -0700506 break
507 }
Nick Harper728eed82016-07-07 17:36:52 -0700508 }
509 }
510
511 if hs.suite == nil {
512 c.sendAlert(alertHandshakeFailure)
513 return errors.New("tls: no cipher suite supported by both client and server")
514 }
515
516 hs.hello.cipherSuite = hs.suite.id
Steven Valdez0ee2e112016-07-15 06:51:15 -0400517 if c.config.Bugs.SendCipherSuite != 0 {
518 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
519 }
520
Nick Harper728eed82016-07-07 17:36:52 -0700521 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
522 hs.finishedHash.discardHandshakeBuffer()
523 hs.writeClientHash(hs.clientHello.marshal())
524
525 // Resolve PSK and compute the early secret.
Nick Harper0b3625b2016-07-25 16:16:28 -0700526 var psk []byte
Steven Valdez803c77a2016-09-06 14:13:43 -0400527 if hs.sessionState != nil {
Steven Valdeza833c352016-11-01 13:39:36 -0400528 psk = hs.sessionState.masterSecret
Nick Harper0b3625b2016-07-25 16:16:28 -0700529 } else {
530 psk = hs.finishedHash.zeroSecret()
Nick Harper0b3625b2016-07-25 16:16:28 -0700531 }
Nick Harper728eed82016-07-07 17:36:52 -0700532
533 earlySecret := hs.finishedHash.extractKey(hs.finishedHash.zeroSecret(), psk)
534
Steven Valdez803c77a2016-09-06 14:13:43 -0400535 hs.hello.hasKeyShare = true
536 if hs.sessionState != nil && config.Bugs.NegotiatePSKResumption {
537 hs.hello.hasKeyShare = false
538 }
539 if config.Bugs.MissingKeyShare {
540 hs.hello.hasKeyShare = false
541 }
542
David Benjamin3baa6e12016-10-07 21:10:38 -0400543 firstHelloRetryRequest := true
544
545ResendHelloRetryRequest:
546 var sendHelloRetryRequest bool
547 helloRetryRequest := &helloRetryRequestMsg{
548 vers: versionToWire(c.vers, c.isDTLS),
549 duplicateExtensions: config.Bugs.DuplicateHelloRetryRequestExtensions,
550 }
551
552 if config.Bugs.AlwaysSendHelloRetryRequest {
553 sendHelloRetryRequest = true
554 }
555
556 if config.Bugs.SendHelloRetryRequestCookie != nil {
557 sendHelloRetryRequest = true
558 helloRetryRequest.cookie = config.Bugs.SendHelloRetryRequestCookie
559 }
560
561 if len(config.Bugs.CustomHelloRetryRequestExtension) > 0 {
562 sendHelloRetryRequest = true
563 helloRetryRequest.customExtension = config.Bugs.CustomHelloRetryRequestExtension
564 }
565
566 var selectedKeyShare *keyShareEntry
Steven Valdez803c77a2016-09-06 14:13:43 -0400567 if hs.hello.hasKeyShare {
Nick Harper728eed82016-07-07 17:36:52 -0700568 // Look for the key share corresponding to our selected curve.
Nick Harper728eed82016-07-07 17:36:52 -0700569 for i := range hs.clientHello.keyShares {
570 if hs.clientHello.keyShares[i].group == selectedCurve {
571 selectedKeyShare = &hs.clientHello.keyShares[i]
572 break
573 }
574 }
575
David Benjamine73c7f42016-08-17 00:29:33 -0400576 if config.Bugs.ExpectMissingKeyShare && selectedKeyShare != nil {
577 return errors.New("tls: expected missing key share")
578 }
579
David Benjamin3baa6e12016-10-07 21:10:38 -0400580 if selectedKeyShare == nil {
581 helloRetryRequest.hasSelectedGroup = true
582 helloRetryRequest.selectedGroup = selectedCurve
Steven Valdez5440fe02016-07-18 12:40:30 -0400583 sendHelloRetryRequest = true
584 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400585 }
586
587 if config.Bugs.SendHelloRetryRequestCurve != 0 {
588 helloRetryRequest.hasSelectedGroup = true
589 helloRetryRequest.selectedGroup = config.Bugs.SendHelloRetryRequestCurve
590 sendHelloRetryRequest = true
591 }
592
593 if config.Bugs.SkipHelloRetryRequest {
594 sendHelloRetryRequest = false
595 }
596
597 if sendHelloRetryRequest {
Steven Valdeza833c352016-11-01 13:39:36 -0400598 oldClientHelloBytes := hs.clientHello.marshal()
David Benjamin3baa6e12016-10-07 21:10:38 -0400599 hs.writeServerHash(helloRetryRequest.marshal())
600 c.writeRecord(recordTypeHandshake, helloRetryRequest.marshal())
601 c.flushHandshake()
602
603 // Read new ClientHello.
604 newMsg, err := c.readHandshake()
605 if err != nil {
606 return err
Steven Valdez5440fe02016-07-18 12:40:30 -0400607 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400608 newClientHello, ok := newMsg.(*clientHelloMsg)
609 if !ok {
610 c.sendAlert(alertUnexpectedMessage)
611 return unexpectedMessageError(newClientHello, newMsg)
612 }
613 hs.writeClientHash(newClientHello.marshal())
Nick Harperdcfbc672016-07-16 17:47:31 +0200614
David Benjamin3baa6e12016-10-07 21:10:38 -0400615 // Check that the new ClientHello matches the old ClientHello,
616 // except for relevant modifications.
617 //
618 // TODO(davidben): Make this check more precise.
619 oldClientHelloCopy := *hs.clientHello
620 oldClientHelloCopy.raw = nil
621 oldClientHelloCopy.hasEarlyData = false
David Benjamin3baa6e12016-10-07 21:10:38 -0400622 newClientHelloCopy := *newClientHello
623 newClientHelloCopy.raw = nil
Nick Harperdcfbc672016-07-16 17:47:31 +0200624
David Benjamin3baa6e12016-10-07 21:10:38 -0400625 if helloRetryRequest.hasSelectedGroup {
626 newKeyShares := newClientHelloCopy.keyShares
Steven Valdeza833c352016-11-01 13:39:36 -0400627 if len(newKeyShares) != 1 || newKeyShares[0].group != helloRetryRequest.selectedGroup {
628 return errors.New("tls: KeyShare from HelloRetryRequest not in new ClientHello")
Nick Harperdcfbc672016-07-16 17:47:31 +0200629 }
Steven Valdeza833c352016-11-01 13:39:36 -0400630 selectedKeyShare = &newKeyShares[0]
631 newClientHelloCopy.keyShares = oldClientHelloCopy.keyShares
Nick Harper728eed82016-07-07 17:36:52 -0700632 }
633
David Benjamin3baa6e12016-10-07 21:10:38 -0400634 if len(helloRetryRequest.cookie) > 0 {
635 if !bytes.Equal(newClientHelloCopy.tls13Cookie, helloRetryRequest.cookie) {
636 return errors.New("tls: cookie from HelloRetryRequest not present in new ClientHello")
637 }
638 newClientHelloCopy.tls13Cookie = nil
639 }
David Benjaminea80f9d2016-11-15 18:19:55 +0900640
641 // PSK binders and obfuscated ticket age are both updated in the
642 // second ClientHello.
643 if len(oldClientHelloCopy.pskIdentities) != len(newClientHelloCopy.pskIdentities) {
644 return errors.New("tls: PSK identity count from old and new ClientHello do not match")
645 }
646 for i, identity := range oldClientHelloCopy.pskIdentities {
647 newClientHelloCopy.pskIdentities[i].obfuscatedTicketAge = identity.obfuscatedTicketAge
648 }
Steven Valdeza833c352016-11-01 13:39:36 -0400649 newClientHelloCopy.pskBinders = oldClientHelloCopy.pskBinders
David Benjamin3baa6e12016-10-07 21:10:38 -0400650
651 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
652 return errors.New("tls: new ClientHello does not match")
653 }
654
655 if firstHelloRetryRequest && config.Bugs.SecondHelloRetryRequest {
656 firstHelloRetryRequest = false
657 goto ResendHelloRetryRequest
658 }
Steven Valdeza833c352016-11-01 13:39:36 -0400659
660 // Verify the PSK binder. Note there may not be a PSK binder if
661 // AcceptAnyBinder is set. See https://crbug.com/115.
662 if hs.sessionState != nil && !config.Bugs.AcceptAnySession {
663 binderToVerify := newClientHello.pskBinders[pskIndex]
664 err := verifyPSKBinder(newClientHello, hs.sessionState, binderToVerify, append(oldClientHelloBytes, helloRetryRequest.marshal()...))
665 if err != nil {
666 return err
667 }
668 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400669 }
670
671 // Resolve ECDHE and compute the handshake secret.
672 var ecdheSecret []byte
673 if hs.hello.hasKeyShare {
Nick Harper728eed82016-07-07 17:36:52 -0700674 // Once a curve has been selected and a key share identified,
675 // the server needs to generate a public value and send it in
676 // the ServerHello.
Steven Valdez5440fe02016-07-18 12:40:30 -0400677 curve, ok := curveForCurveID(selectedCurve)
Nick Harper728eed82016-07-07 17:36:52 -0700678 if !ok {
679 panic("tls: server failed to look up curve ID")
680 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400681 c.curveID = selectedCurve
682
683 var peerKey []byte
684 if config.Bugs.SkipHelloRetryRequest {
685 // If skipping HelloRetryRequest, use a random key to
686 // avoid crashing.
687 curve2, _ := curveForCurveID(selectedCurve)
688 var err error
689 peerKey, err = curve2.offer(config.rand())
690 if err != nil {
691 return err
692 }
693 } else {
694 peerKey = selectedKeyShare.keyExchange
695 }
696
Nick Harper728eed82016-07-07 17:36:52 -0700697 var publicKey []byte
698 var err error
Steven Valdez5440fe02016-07-18 12:40:30 -0400699 publicKey, ecdheSecret, err = curve.accept(config.rand(), peerKey)
Nick Harper728eed82016-07-07 17:36:52 -0700700 if err != nil {
701 c.sendAlert(alertHandshakeFailure)
702 return err
703 }
704 hs.hello.hasKeyShare = true
Steven Valdez0ee2e112016-07-15 06:51:15 -0400705
Steven Valdez5440fe02016-07-18 12:40:30 -0400706 curveID := selectedCurve
Steven Valdez0ee2e112016-07-15 06:51:15 -0400707 if c.config.Bugs.SendCurve != 0 {
708 curveID = config.Bugs.SendCurve
709 }
710 if c.config.Bugs.InvalidECDHPoint {
711 publicKey[0] ^= 0xff
712 }
713
Nick Harper728eed82016-07-07 17:36:52 -0700714 hs.hello.keyShare = keyShareEntry{
Steven Valdez0ee2e112016-07-15 06:51:15 -0400715 group: curveID,
Nick Harper728eed82016-07-07 17:36:52 -0700716 keyExchange: publicKey,
717 }
Steven Valdez143e8b32016-07-11 13:19:03 -0400718
719 if config.Bugs.EncryptedExtensionsWithKeyShare {
720 encryptedExtensions.extensions.hasKeyShare = true
721 encryptedExtensions.extensions.keyShare = keyShareEntry{
722 group: curveID,
723 keyExchange: publicKey,
724 }
725 }
Nick Harper728eed82016-07-07 17:36:52 -0700726 } else {
727 ecdheSecret = hs.finishedHash.zeroSecret()
728 }
729
730 // Send unencrypted ServerHello.
731 hs.writeServerHash(hs.hello.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400732 if config.Bugs.PartialEncryptedExtensionsWithServerHello {
733 helloBytes := hs.hello.marshal()
734 toWrite := make([]byte, 0, len(helloBytes)+1)
735 toWrite = append(toWrite, helloBytes...)
736 toWrite = append(toWrite, typeEncryptedExtensions)
737 c.writeRecord(recordTypeHandshake, toWrite)
738 } else {
739 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
740 }
Nick Harper728eed82016-07-07 17:36:52 -0700741 c.flushHandshake()
742
743 // Compute the handshake secret.
744 handshakeSecret := hs.finishedHash.extractKey(earlySecret, ecdheSecret)
745
746 // Switch to handshake traffic keys.
Steven Valdezc4aa7272016-10-03 12:25:56 -0400747 serverHandshakeTrafficSecret := hs.finishedHash.deriveSecret(handshakeSecret, serverHandshakeTrafficLabel)
Steven Valdeza833c352016-11-01 13:39:36 -0400748 c.out.useTrafficSecret(c.vers, hs.suite, serverHandshakeTrafficSecret, serverWrite)
Steven Valdezc4aa7272016-10-03 12:25:56 -0400749 clientHandshakeTrafficSecret := hs.finishedHash.deriveSecret(handshakeSecret, clientHandshakeTrafficLabel)
Steven Valdeza833c352016-11-01 13:39:36 -0400750 c.in.useTrafficSecret(c.vers, hs.suite, clientHandshakeTrafficSecret, clientWrite)
David Benjamin615119a2016-07-06 19:22:55 -0700751
Nick Harper728eed82016-07-07 17:36:52 -0700752 // Send EncryptedExtensions.
753 hs.writeServerHash(encryptedExtensions.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400754 if config.Bugs.PartialEncryptedExtensionsWithServerHello {
755 // The first byte has already been sent.
756 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()[1:])
757 } else {
758 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal())
759 }
Nick Harper728eed82016-07-07 17:36:52 -0700760
Steven Valdeza833c352016-11-01 13:39:36 -0400761 if hs.sessionState == nil {
Nick Harper728eed82016-07-07 17:36:52 -0700762 if config.ClientAuth >= RequestClientCert {
David Benjamin8d343b42016-07-09 14:26:01 -0700763 // Request a client certificate
764 certReq := &certificateRequestMsg{
765 hasSignatureAlgorithm: true,
766 hasRequestContext: true,
David Benjamin8a8349b2016-08-18 02:32:23 -0400767 requestContext: config.Bugs.SendRequestContext,
David Benjamin8d343b42016-07-09 14:26:01 -0700768 }
769 if !config.Bugs.NoSignatureAlgorithms {
David Benjaminf74ec792016-07-13 21:18:49 -0400770 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin8d343b42016-07-09 14:26:01 -0700771 }
772
773 // An empty list of certificateAuthorities signals to
774 // the client that it may send any certificate in response
775 // to our request. When we know the CAs we trust, then
776 // we can send them down, so that the client can choose
777 // an appropriate certificate to give to us.
778 if config.ClientCAs != nil {
779 certReq.certificateAuthorities = config.ClientCAs.Subjects()
780 }
781 hs.writeServerHash(certReq.marshal())
782 c.writeRecord(recordTypeHandshake, certReq.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700783 }
784
785 certMsg := &certificateMsg{
786 hasRequestContext: true,
787 }
788 if !config.Bugs.EmptyCertificateList {
Steven Valdeza833c352016-11-01 13:39:36 -0400789 for i, certData := range hs.cert.Certificate {
790 cert := certificateEntry{
791 data: certData,
792 }
793 if i == 0 {
794 if hs.clientHello.ocspStapling {
795 cert.ocspResponse = hs.cert.OCSPStaple
796 }
797 if hs.clientHello.sctListSupported {
798 cert.sctList = hs.cert.SignedCertificateTimestampList
799 }
800 cert.duplicateExtensions = config.Bugs.SendDuplicateCertExtensions
801 cert.extraExtension = config.Bugs.SendExtensionOnCertificate
802 } else {
803 if config.Bugs.SendOCSPOnIntermediates != nil {
804 cert.ocspResponse = config.Bugs.SendOCSPOnIntermediates
805 }
806 if config.Bugs.SendSCTOnIntermediates != nil {
807 cert.sctList = config.Bugs.SendSCTOnIntermediates
808 }
809 }
810 certMsg.certificates = append(certMsg.certificates, cert)
811 }
Nick Harper728eed82016-07-07 17:36:52 -0700812 }
David Benjamin1edae6b2016-07-13 16:58:23 -0400813 certMsgBytes := certMsg.marshal()
David Benjamin1edae6b2016-07-13 16:58:23 -0400814 hs.writeServerHash(certMsgBytes)
815 c.writeRecord(recordTypeHandshake, certMsgBytes)
Nick Harper728eed82016-07-07 17:36:52 -0700816
817 certVerify := &certificateVerifyMsg{
818 hasSignatureAlgorithm: true,
819 }
820
821 // Determine the hash to sign.
822 privKey := hs.cert.PrivateKey
823
824 var err error
825 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, config, hs.clientHello.signatureAlgorithms)
826 if err != nil {
827 c.sendAlert(alertInternalError)
828 return err
829 }
830
831 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
832 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
833 if err != nil {
834 c.sendAlert(alertInternalError)
835 return err
836 }
837
Steven Valdez0ee2e112016-07-15 06:51:15 -0400838 if config.Bugs.SendSignatureAlgorithm != 0 {
839 certVerify.signatureAlgorithm = config.Bugs.SendSignatureAlgorithm
840 }
841
Nick Harper728eed82016-07-07 17:36:52 -0700842 hs.writeServerHash(certVerify.marshal())
843 c.writeRecord(recordTypeHandshake, certVerify.marshal())
Steven Valdez803c77a2016-09-06 14:13:43 -0400844 } else if hs.sessionState != nil {
Nick Harper0b3625b2016-07-25 16:16:28 -0700845 // Pick up certificates from the session instead.
David Benjamin5ecb88b2016-10-04 17:51:35 -0400846 if len(hs.sessionState.certificates) > 0 {
Nick Harper0b3625b2016-07-25 16:16:28 -0700847 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
848 return err
849 }
850 }
Nick Harper728eed82016-07-07 17:36:52 -0700851 }
852
853 finished := new(finishedMsg)
Steven Valdezc4aa7272016-10-03 12:25:56 -0400854 finished.verifyData = hs.finishedHash.serverSum(serverHandshakeTrafficSecret)
Nick Harper728eed82016-07-07 17:36:52 -0700855 if config.Bugs.BadFinished {
856 finished.verifyData[0]++
857 }
858 hs.writeServerHash(finished.marshal())
859 c.writeRecord(recordTypeHandshake, finished.marshal())
David Benjamin02edcd02016-07-27 17:40:37 -0400860 if c.config.Bugs.SendExtraFinished {
861 c.writeRecord(recordTypeHandshake, finished.marshal())
862 }
Nick Harper728eed82016-07-07 17:36:52 -0700863 c.flushHandshake()
864
865 // The various secrets do not incorporate the client's final leg, so
866 // derive them now before updating the handshake context.
867 masterSecret := hs.finishedHash.extractKey(handshakeSecret, hs.finishedHash.zeroSecret())
Steven Valdezc4aa7272016-10-03 12:25:56 -0400868 clientTrafficSecret := hs.finishedHash.deriveSecret(masterSecret, clientApplicationTrafficLabel)
869 serverTrafficSecret := hs.finishedHash.deriveSecret(masterSecret, serverApplicationTrafficLabel)
Steven Valdeza833c352016-11-01 13:39:36 -0400870 c.exporterSecret = hs.finishedHash.deriveSecret(masterSecret, exporterLabel)
Nick Harper728eed82016-07-07 17:36:52 -0700871
David Benjamin2aad4062016-07-14 23:15:40 -0400872 // Switch to application data keys on write. In particular, any alerts
873 // from the client certificate are sent over these keys.
Steven Valdeza833c352016-11-01 13:39:36 -0400874 c.out.useTrafficSecret(c.vers, hs.suite, serverTrafficSecret, serverWrite)
David Benjamin2aad4062016-07-14 23:15:40 -0400875
Nick Harper728eed82016-07-07 17:36:52 -0700876 // If we requested a client certificate, then the client must send a
877 // certificate message, even if it's empty.
878 if config.ClientAuth >= RequestClientCert {
David Benjamin8d343b42016-07-09 14:26:01 -0700879 msg, err := c.readHandshake()
880 if err != nil {
881 return err
882 }
883
884 certMsg, ok := msg.(*certificateMsg)
885 if !ok {
886 c.sendAlert(alertUnexpectedMessage)
887 return unexpectedMessageError(certMsg, msg)
888 }
889 hs.writeClientHash(certMsg.marshal())
890
891 if len(certMsg.certificates) == 0 {
892 // The client didn't actually send a certificate
893 switch config.ClientAuth {
894 case RequireAnyClientCert, RequireAndVerifyClientCert:
David Benjamin1db9e1b2016-10-07 20:51:43 -0400895 c.sendAlert(alertCertificateRequired)
David Benjamin8d343b42016-07-09 14:26:01 -0700896 return errors.New("tls: client didn't provide a certificate")
897 }
898 }
899
Steven Valdeza833c352016-11-01 13:39:36 -0400900 var certs [][]byte
901 for _, cert := range certMsg.certificates {
902 certs = append(certs, cert.data)
903 // OCSP responses and SCT lists are not negotiated in
904 // client certificates.
905 if cert.ocspResponse != nil || cert.sctList != nil {
906 c.sendAlert(alertUnsupportedExtension)
907 return errors.New("tls: unexpected extensions in the client certificate")
908 }
909 }
910 pub, err := hs.processCertsFromClient(certs)
David Benjamin8d343b42016-07-09 14:26:01 -0700911 if err != nil {
912 return err
913 }
914
915 if len(c.peerCertificates) > 0 {
916 msg, err = c.readHandshake()
917 if err != nil {
918 return err
919 }
920
921 certVerify, ok := msg.(*certificateVerifyMsg)
922 if !ok {
923 c.sendAlert(alertUnexpectedMessage)
924 return unexpectedMessageError(certVerify, msg)
925 }
926
David Benjaminf74ec792016-07-13 21:18:49 -0400927 c.peerSignatureAlgorithm = certVerify.signatureAlgorithm
David Benjamin8d343b42016-07-09 14:26:01 -0700928 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
929 if err := verifyMessage(c.vers, pub, config, certVerify.signatureAlgorithm, input, certVerify.signature); err != nil {
930 c.sendAlert(alertBadCertificate)
931 return err
932 }
933 hs.writeClientHash(certVerify.marshal())
934 }
Nick Harper728eed82016-07-07 17:36:52 -0700935 }
936
Nick Harper60a85cb2016-09-23 16:25:11 -0700937 if encryptedExtensions.extensions.channelIDRequested {
938 msg, err := c.readHandshake()
939 if err != nil {
940 return err
941 }
942 channelIDMsg, ok := msg.(*channelIDMsg)
943 if !ok {
944 c.sendAlert(alertUnexpectedMessage)
945 return unexpectedMessageError(channelIDMsg, msg)
946 }
947 channelIDHash := crypto.SHA256.New()
948 channelIDHash.Write(hs.finishedHash.certificateVerifyInput(channelIDContextTLS13))
949 channelID, err := verifyChannelIDMessage(channelIDMsg, channelIDHash.Sum(nil))
950 if err != nil {
951 return err
952 }
953 c.channelID = channelID
954
955 hs.writeClientHash(channelIDMsg.marshal())
956 }
957
Nick Harper728eed82016-07-07 17:36:52 -0700958 // Read the client Finished message.
959 msg, err := c.readHandshake()
960 if err != nil {
961 return err
962 }
963 clientFinished, ok := msg.(*finishedMsg)
964 if !ok {
965 c.sendAlert(alertUnexpectedMessage)
966 return unexpectedMessageError(clientFinished, msg)
967 }
968
Steven Valdezc4aa7272016-10-03 12:25:56 -0400969 verify := hs.finishedHash.clientSum(clientHandshakeTrafficSecret)
Nick Harper728eed82016-07-07 17:36:52 -0700970 if len(verify) != len(clientFinished.verifyData) ||
971 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
972 c.sendAlert(alertHandshakeFailure)
973 return errors.New("tls: client's Finished message was incorrect")
974 }
David Benjamin97a0a082016-07-13 17:57:35 -0400975 hs.writeClientHash(clientFinished.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700976
David Benjamin2aad4062016-07-14 23:15:40 -0400977 // Switch to application data keys on read.
Steven Valdeza833c352016-11-01 13:39:36 -0400978 c.in.useTrafficSecret(c.vers, hs.suite, clientTrafficSecret, clientWrite)
Nick Harper728eed82016-07-07 17:36:52 -0700979
Nick Harper728eed82016-07-07 17:36:52 -0700980 c.cipherSuite = hs.suite
David Benjamin58104882016-07-18 01:25:41 +0200981 c.resumptionSecret = hs.finishedHash.deriveSecret(masterSecret, resumptionLabel)
982
983 // TODO(davidben): Allow configuring the number of tickets sent for
984 // testing.
Steven Valdeza833c352016-11-01 13:39:36 -0400985 if !c.config.SessionTicketsDisabled && foundKEMode {
David Benjamin58104882016-07-18 01:25:41 +0200986 ticketCount := 2
987 for i := 0; i < ticketCount; i++ {
988 c.SendNewSessionTicket()
989 }
990 }
Nick Harper728eed82016-07-07 17:36:52 -0700991 return nil
992}
993
David Benjaminf25dda92016-07-04 10:05:26 -0700994// processClientHello processes the ClientHello message from the client and
995// decides whether we will perform session resumption.
996func (hs *serverHandshakeState) processClientHello() (isResume bool, err error) {
997 config := hs.c.config
998 c := hs.c
999
1000 hs.hello = &serverHelloMsg{
1001 isDTLS: c.isDTLS,
David Benjamin3c6a1ea2016-09-26 18:30:05 -04001002 vers: versionToWire(c.vers, c.isDTLS),
David Benjaminb1dd8cd2016-09-26 19:20:48 -04001003 versOverride: config.Bugs.SendServerHelloVersion,
David Benjaminf25dda92016-07-04 10:05:26 -07001004 compressionMethod: compressionNone,
1005 }
1006
1007 hs.hello.random = make([]byte, 32)
1008 _, err = io.ReadFull(config.rand(), hs.hello.random)
1009 if err != nil {
1010 c.sendAlert(alertInternalError)
1011 return false, err
1012 }
David Benjamina128a552016-10-13 14:26:33 -04001013 // Signal downgrades in the server random, per draft-ietf-tls-tls13-16,
1014 // section 4.1.3.
Nick Harper85f20c22016-07-04 10:11:59 -07001015 if c.vers <= VersionTLS12 && config.maxVersion(c.isDTLS) >= VersionTLS13 {
David Benjamin1f61f0d2016-07-10 12:20:35 -04001016 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS13)
Nick Harper85f20c22016-07-04 10:11:59 -07001017 }
1018 if c.vers <= VersionTLS11 && config.maxVersion(c.isDTLS) == VersionTLS12 {
David Benjamin1f61f0d2016-07-10 12:20:35 -04001019 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS12)
Nick Harper85f20c22016-07-04 10:11:59 -07001020 }
David Benjaminf25dda92016-07-04 10:05:26 -07001021
1022 foundCompression := false
1023 // We only support null compression, so check that the client offered it.
1024 for _, compression := range hs.clientHello.compressionMethods {
1025 if compression == compressionNone {
1026 foundCompression = true
1027 break
1028 }
1029 }
1030
1031 if !foundCompression {
1032 c.sendAlert(alertHandshakeFailure)
1033 return false, errors.New("tls: client does not support uncompressed connections")
1034 }
David Benjamin7d79f832016-07-04 09:20:45 -07001035
1036 if err := hs.processClientExtensions(&hs.hello.extensions); err != nil {
1037 return false, err
Adam Langley09505632015-07-30 18:10:13 -07001038 }
Adam Langley95c29f32014-06-20 12:00:00 -07001039
1040 supportedCurve := false
1041 preferredCurves := config.curvePreferences()
1042Curves:
1043 for _, curve := range hs.clientHello.supportedCurves {
1044 for _, supported := range preferredCurves {
1045 if supported == curve {
1046 supportedCurve = true
1047 break Curves
1048 }
1049 }
1050 }
1051
1052 supportedPointFormat := false
1053 for _, pointFormat := range hs.clientHello.supportedPoints {
1054 if pointFormat == pointFormatUncompressed {
1055 supportedPointFormat = true
1056 break
1057 }
1058 }
1059 hs.ellipticOk = supportedCurve && supportedPointFormat
1060
Adam Langley95c29f32014-06-20 12:00:00 -07001061 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
1062
David Benjamin4b27d9f2015-05-12 22:42:52 -04001063 // For test purposes, check that the peer never offers a session when
1064 // renegotiating.
1065 if c.cipherSuite != nil && len(hs.clientHello.sessionId) > 0 && c.config.Bugs.FailIfResumeOnRenego {
1066 return false, errors.New("tls: offered resumption on renegotiation")
1067 }
1068
David Benjamindd6fed92015-10-23 17:41:12 -04001069 if c.config.Bugs.FailIfSessionOffered && (len(hs.clientHello.sessionTicket) > 0 || len(hs.clientHello.sessionId) > 0) {
1070 return false, errors.New("tls: client offered a session ticket or ID")
1071 }
1072
Adam Langley95c29f32014-06-20 12:00:00 -07001073 if hs.checkForResumption() {
1074 return true, nil
1075 }
1076
Adam Langley95c29f32014-06-20 12:00:00 -07001077 var preferenceList, supportedList []uint16
1078 if c.config.PreferServerCipherSuites {
1079 preferenceList = c.config.cipherSuites()
1080 supportedList = hs.clientHello.cipherSuites
1081 } else {
1082 preferenceList = hs.clientHello.cipherSuites
1083 supportedList = c.config.cipherSuites()
1084 }
1085
1086 for _, id := range preferenceList {
Steven Valdez803c77a2016-09-06 14:13:43 -04001087 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
Adam Langley95c29f32014-06-20 12:00:00 -07001088 break
1089 }
1090 }
1091
1092 if hs.suite == nil {
1093 c.sendAlert(alertHandshakeFailure)
1094 return false, errors.New("tls: no cipher suite supported by both client and server")
1095 }
1096
1097 return false, nil
1098}
1099
David Benjamin7d79f832016-07-04 09:20:45 -07001100// processClientExtensions processes all ClientHello extensions not directly
1101// related to cipher suite negotiation and writes responses in serverExtensions.
1102func (hs *serverHandshakeState) processClientExtensions(serverExtensions *serverExtensions) error {
1103 config := hs.c.config
1104 c := hs.c
1105
David Benjamin8d315d72016-07-18 01:03:18 +02001106 if c.vers < VersionTLS13 || config.Bugs.NegotiateRenegotiationInfoAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -07001107 if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) {
1108 c.sendAlert(alertHandshakeFailure)
1109 return errors.New("tls: renegotiation mismatch")
David Benjamin7d79f832016-07-04 09:20:45 -07001110 }
David Benjamin7d79f832016-07-04 09:20:45 -07001111
Nick Harper728eed82016-07-07 17:36:52 -07001112 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
1113 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.clientVerify...)
1114 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.serverVerify...)
1115 if c.config.Bugs.BadRenegotiationInfo {
1116 serverExtensions.secureRenegotiation[0] ^= 0x80
1117 }
1118 } else {
1119 serverExtensions.secureRenegotiation = hs.clientHello.secureRenegotiation
1120 }
1121
1122 if c.noRenegotiationInfo() {
1123 serverExtensions.secureRenegotiation = nil
1124 }
David Benjamin7d79f832016-07-04 09:20:45 -07001125 }
1126
1127 serverExtensions.duplicateExtension = c.config.Bugs.DuplicateExtension
1128
1129 if len(hs.clientHello.serverName) > 0 {
1130 c.serverName = hs.clientHello.serverName
1131 }
1132 if len(config.Certificates) == 0 {
1133 c.sendAlert(alertInternalError)
1134 return errors.New("tls: no certificates configured")
1135 }
1136 hs.cert = &config.Certificates[0]
1137 if len(hs.clientHello.serverName) > 0 {
1138 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
1139 }
1140 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
1141 return errors.New("tls: unexpected server name")
1142 }
1143
1144 if len(hs.clientHello.alpnProtocols) > 0 {
1145 if proto := c.config.Bugs.ALPNProtocol; proto != nil {
1146 serverExtensions.alpnProtocol = *proto
1147 serverExtensions.alpnProtocolEmpty = len(*proto) == 0
1148 c.clientProtocol = *proto
1149 c.usedALPN = true
1150 } else if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
1151 serverExtensions.alpnProtocol = selectedProto
1152 c.clientProtocol = selectedProto
1153 c.usedALPN = true
1154 }
1155 }
Nick Harper728eed82016-07-07 17:36:52 -07001156
David Benjamin0c40a962016-08-01 12:05:50 -04001157 if len(c.config.Bugs.SendALPN) > 0 {
1158 serverExtensions.alpnProtocol = c.config.Bugs.SendALPN
1159 }
1160
David Benjamin8d315d72016-07-18 01:03:18 +02001161 if c.vers < VersionTLS13 || config.Bugs.NegotiateNPNAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -07001162 if len(hs.clientHello.alpnProtocols) == 0 || c.config.Bugs.NegotiateALPNAndNPN {
1163 // Although sending an empty NPN extension is reasonable, Firefox has
1164 // had a bug around this. Best to send nothing at all if
1165 // config.NextProtos is empty. See
1166 // https://code.google.com/p/go/issues/detail?id=5445.
1167 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
1168 serverExtensions.nextProtoNeg = true
1169 serverExtensions.nextProtos = config.NextProtos
Steven Valdeza833c352016-11-01 13:39:36 -04001170 serverExtensions.npnAfterAlpn = config.Bugs.SwapNPNAndALPN
Nick Harper728eed82016-07-07 17:36:52 -07001171 }
David Benjamin7d79f832016-07-04 09:20:45 -07001172 }
Steven Valdez143e8b32016-07-11 13:19:03 -04001173 }
David Benjamin7d79f832016-07-04 09:20:45 -07001174
David Benjamin8d315d72016-07-18 01:03:18 +02001175 if c.vers < VersionTLS13 || config.Bugs.NegotiateEMSAtAllVersions {
David Benjamin163c9562016-08-29 23:14:17 -04001176 disableEMS := config.Bugs.NoExtendedMasterSecret
1177 if c.cipherSuite != nil {
1178 disableEMS = config.Bugs.NoExtendedMasterSecretOnRenegotiation
1179 }
1180 serverExtensions.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !disableEMS
Steven Valdez143e8b32016-07-11 13:19:03 -04001181 }
David Benjamin7d79f832016-07-04 09:20:45 -07001182
Nick Harper60a85cb2016-09-23 16:25:11 -07001183 if hs.clientHello.channelIDSupported && config.RequestChannelID {
1184 serverExtensions.channelIDRequested = true
David Benjamin7d79f832016-07-04 09:20:45 -07001185 }
1186
1187 if hs.clientHello.srtpProtectionProfiles != nil {
1188 SRTPLoop:
1189 for _, p1 := range c.config.SRTPProtectionProfiles {
1190 for _, p2 := range hs.clientHello.srtpProtectionProfiles {
1191 if p1 == p2 {
1192 serverExtensions.srtpProtectionProfile = p1
1193 c.srtpProtectionProfile = p1
1194 break SRTPLoop
1195 }
1196 }
1197 }
1198 }
1199
1200 if c.config.Bugs.SendSRTPProtectionProfile != 0 {
1201 serverExtensions.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
1202 }
1203
1204 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
1205 if hs.clientHello.customExtension != *expected {
1206 return fmt.Errorf("tls: bad custom extension contents %q", hs.clientHello.customExtension)
1207 }
1208 }
1209 serverExtensions.customExtension = config.Bugs.CustomExtension
1210
Steven Valdez143e8b32016-07-11 13:19:03 -04001211 if c.config.Bugs.AdvertiseTicketExtension {
1212 serverExtensions.ticketSupported = true
1213 }
1214
David Benjamin65ac9972016-09-02 21:35:25 -04001215 if !hs.clientHello.hasGREASEExtension && config.Bugs.ExpectGREASE {
1216 return errors.New("tls: no GREASE extension found")
1217 }
1218
David Benjamin7d79f832016-07-04 09:20:45 -07001219 return nil
1220}
1221
Adam Langley95c29f32014-06-20 12:00:00 -07001222// checkForResumption returns true if we should perform resumption on this connection.
1223func (hs *serverHandshakeState) checkForResumption() bool {
1224 c := hs.c
1225
David Benjamin405da482016-08-08 17:25:07 -04001226 ticket := hs.clientHello.sessionTicket
1227 if len(ticket) == 0 && len(hs.clientHello.pskIdentities) > 0 && c.config.Bugs.AcceptAnySession {
Steven Valdez5b986082016-09-01 12:29:49 -04001228 ticket = hs.clientHello.pskIdentities[0].ticket
David Benjamin405da482016-08-08 17:25:07 -04001229 }
1230 if len(ticket) > 0 {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001231 if c.config.SessionTicketsDisabled {
1232 return false
1233 }
David Benjaminb0c8db72014-09-24 15:19:56 -04001234
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001235 var ok bool
David Benjamin405da482016-08-08 17:25:07 -04001236 if hs.sessionState, ok = c.decryptTicket(ticket); !ok {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001237 return false
1238 }
1239 } else {
1240 if c.config.ServerSessionCache == nil {
1241 return false
1242 }
1243
1244 var ok bool
1245 sessionId := string(hs.clientHello.sessionId)
1246 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
1247 return false
1248 }
Adam Langley95c29f32014-06-20 12:00:00 -07001249 }
1250
Steven Valdez803c77a2016-09-06 14:13:43 -04001251 if c.config.Bugs.AcceptAnySession {
1252 // Replace the cipher suite with one known to work, to test
1253 // cross-version resumption attempts.
1254 hs.sessionState.cipherSuite = TLS_RSA_WITH_AES_128_CBC_SHA
1255 } else {
David Benjamin405da482016-08-08 17:25:07 -04001256 // Never resume a session for a different SSL version.
1257 if c.vers != hs.sessionState.vers {
1258 return false
Adam Langley95c29f32014-06-20 12:00:00 -07001259 }
David Benjamin405da482016-08-08 17:25:07 -04001260
1261 cipherSuiteOk := false
1262 // Check that the client is still offering the ciphersuite in the session.
1263 for _, id := range hs.clientHello.cipherSuites {
1264 if id == hs.sessionState.cipherSuite {
1265 cipherSuiteOk = true
1266 break
1267 }
1268 }
1269 if !cipherSuiteOk {
1270 return false
1271 }
Adam Langley95c29f32014-06-20 12:00:00 -07001272 }
1273
1274 // Check that we also support the ciphersuite from the session.
Steven Valdez803c77a2016-09-06 14:13:43 -04001275 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), c.vers, hs.ellipticOk, hs.ecdsaOk)
1276
Adam Langley95c29f32014-06-20 12:00:00 -07001277 if hs.suite == nil {
1278 return false
1279 }
1280
1281 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
1282 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
1283 if needClientCerts && !sessionHasClientCerts {
1284 return false
1285 }
1286 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
1287 return false
1288 }
1289
1290 return true
1291}
1292
1293func (hs *serverHandshakeState) doResumeHandshake() error {
1294 c := hs.c
1295
1296 hs.hello.cipherSuite = hs.suite.id
David Benjaminece3de92015-03-16 18:02:20 -04001297 if c.config.Bugs.SendCipherSuite != 0 {
1298 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
1299 }
Adam Langley95c29f32014-06-20 12:00:00 -07001300 // We echo the client's session ID in the ServerHello to let it know
1301 // that we're doing a resumption.
1302 hs.hello.sessionId = hs.clientHello.sessionId
Nick Harperb3d51be2016-07-01 11:43:18 -04001303 hs.hello.extensions.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -07001304
David Benjamin80d1b352016-05-04 19:19:06 -04001305 if c.config.Bugs.SendSCTListOnResume != nil {
Nick Harperb3d51be2016-07-01 11:43:18 -04001306 hs.hello.extensions.sctList = c.config.Bugs.SendSCTListOnResume
David Benjamin80d1b352016-05-04 19:19:06 -04001307 }
1308
David Benjamindaa88502016-10-04 16:32:16 -04001309 if c.config.Bugs.SendOCSPResponseOnResume != nil {
1310 // There is no way, syntactically, to send an OCSP response on a
1311 // resumption handshake.
1312 hs.hello.extensions.ocspStapling = true
1313 }
1314
Adam Langley95c29f32014-06-20 12:00:00 -07001315 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -04001316 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -04001317 hs.writeClientHash(hs.clientHello.marshal())
1318 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001319
1320 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
1321
1322 if len(hs.sessionState.certificates) > 0 {
1323 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
1324 return err
1325 }
1326 }
1327
1328 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -07001329 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -07001330
1331 return nil
1332}
1333
1334func (hs *serverHandshakeState) doFullHandshake() error {
1335 config := hs.c.config
1336 c := hs.c
1337
David Benjamin48cae082014-10-27 01:06:24 -04001338 isPSK := hs.suite.flags&suitePSK != 0
1339 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001340 hs.hello.extensions.ocspStapling = true
Adam Langley95c29f32014-06-20 12:00:00 -07001341 }
1342
David Benjamin61f95272014-11-25 01:55:35 -05001343 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001344 hs.hello.extensions.sctList = hs.cert.SignedCertificateTimestampList
David Benjamin61f95272014-11-25 01:55:35 -05001345 }
1346
Nick Harperb3d51be2016-07-01 11:43:18 -04001347 hs.hello.extensions.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
Adam Langley95c29f32014-06-20 12:00:00 -07001348 hs.hello.cipherSuite = hs.suite.id
David Benjamin6095de82014-12-27 01:50:38 -05001349 if config.Bugs.SendCipherSuite != 0 {
1350 hs.hello.cipherSuite = config.Bugs.SendCipherSuite
1351 }
Nick Harperb3d51be2016-07-01 11:43:18 -04001352 c.extendedMasterSecret = hs.hello.extensions.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -07001353
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001354 // Generate a session ID if we're to save the session.
Nick Harperb3d51be2016-07-01 11:43:18 -04001355 if !hs.hello.extensions.ticketSupported && config.ServerSessionCache != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001356 hs.hello.sessionId = make([]byte, 32)
1357 if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
1358 c.sendAlert(alertInternalError)
1359 return errors.New("tls: short read from Rand: " + err.Error())
1360 }
1361 }
1362
Adam Langley95c29f32014-06-20 12:00:00 -07001363 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -04001364 hs.writeClientHash(hs.clientHello.marshal())
1365 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001366
David Benjaminabe94e32016-09-04 14:18:58 -04001367 if config.Bugs.SendSNIWarningAlert {
1368 c.SendAlert(alertLevelWarning, alertUnrecognizedName)
1369 }
1370
Adam Langley95c29f32014-06-20 12:00:00 -07001371 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
1372
David Benjamin48cae082014-10-27 01:06:24 -04001373 if !isPSK {
1374 certMsg := new(certificateMsg)
David Benjamin8923c0b2015-06-07 11:42:34 -04001375 if !config.Bugs.EmptyCertificateList {
Steven Valdeza833c352016-11-01 13:39:36 -04001376 for _, certData := range hs.cert.Certificate {
1377 certMsg.certificates = append(certMsg.certificates, certificateEntry{
1378 data: certData,
1379 })
1380 }
David Benjamin8923c0b2015-06-07 11:42:34 -04001381 }
David Benjamin48cae082014-10-27 01:06:24 -04001382 if !config.Bugs.UnauthenticatedECDH {
David Benjaminbcb2d912015-02-24 23:45:43 -05001383 certMsgBytes := certMsg.marshal()
David Benjaminbcb2d912015-02-24 23:45:43 -05001384 hs.writeServerHash(certMsgBytes)
1385 c.writeRecord(recordTypeHandshake, certMsgBytes)
David Benjamin48cae082014-10-27 01:06:24 -04001386 }
David Benjamin1c375dd2014-07-12 00:48:23 -04001387 }
Adam Langley95c29f32014-06-20 12:00:00 -07001388
Nick Harperb3d51be2016-07-01 11:43:18 -04001389 if hs.hello.extensions.ocspStapling && !c.config.Bugs.SkipCertificateStatus {
Adam Langley95c29f32014-06-20 12:00:00 -07001390 certStatus := new(certificateStatusMsg)
1391 certStatus.statusType = statusTypeOCSP
1392 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -04001393 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001394 c.writeRecord(recordTypeHandshake, certStatus.marshal())
1395 }
1396
1397 keyAgreement := hs.suite.ka(c.vers)
1398 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
1399 if err != nil {
1400 c.sendAlert(alertHandshakeFailure)
1401 return err
1402 }
Steven Valdez5440fe02016-07-18 12:40:30 -04001403 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
1404 c.curveID = ecdhe.curveID
1405 }
David Benjamin9c651c92014-07-12 13:27:45 -04001406 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -04001407 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001408 c.writeRecord(recordTypeHandshake, skx.marshal())
1409 }
1410
1411 if config.ClientAuth >= RequestClientCert {
1412 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -04001413 certReq := &certificateRequestMsg{
1414 certificateTypes: config.ClientCertificateTypes,
1415 }
1416 if certReq.certificateTypes == nil {
1417 certReq.certificateTypes = []byte{
1418 byte(CertTypeRSASign),
1419 byte(CertTypeECDSASign),
1420 }
Adam Langley95c29f32014-06-20 12:00:00 -07001421 }
1422 if c.vers >= VersionTLS12 {
Nick Harper60edffd2016-06-21 15:19:24 -07001423 certReq.hasSignatureAlgorithm = true
1424 if !config.Bugs.NoSignatureAlgorithms {
David Benjamin7a41d372016-07-09 11:21:54 -07001425 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin000800a2014-11-14 01:43:59 -05001426 }
Adam Langley95c29f32014-06-20 12:00:00 -07001427 }
1428
1429 // An empty list of certificateAuthorities signals to
1430 // the client that it may send any certificate in response
1431 // to our request. When we know the CAs we trust, then
1432 // we can send them down, so that the client can choose
1433 // an appropriate certificate to give to us.
1434 if config.ClientCAs != nil {
1435 certReq.certificateAuthorities = config.ClientCAs.Subjects()
1436 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001437 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001438 c.writeRecord(recordTypeHandshake, certReq.marshal())
1439 }
1440
1441 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001442 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001443 c.writeRecord(recordTypeHandshake, helloDone.marshal())
David Benjamin582ba042016-07-07 12:33:25 -07001444 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001445
1446 var pub crypto.PublicKey // public key for client auth, if any
1447
David Benjamin83f90402015-01-27 01:09:43 -05001448 if err := c.simulatePacketLoss(nil); err != nil {
1449 return err
1450 }
Adam Langley95c29f32014-06-20 12:00:00 -07001451 msg, err := c.readHandshake()
1452 if err != nil {
1453 return err
1454 }
1455
1456 var ok bool
1457 // If we requested a client certificate, then the client must send a
1458 // certificate message, even if it's empty.
1459 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -04001460 var certMsg *certificateMsg
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001461 var certificates [][]byte
1462 if certMsg, ok = msg.(*certificateMsg); ok {
1463 if c.vers == VersionSSL30 && len(certMsg.certificates) == 0 {
1464 return errors.New("tls: empty certificate message in SSL 3.0")
1465 }
1466
1467 hs.writeClientHash(certMsg.marshal())
Steven Valdeza833c352016-11-01 13:39:36 -04001468 for _, cert := range certMsg.certificates {
1469 certificates = append(certificates, cert.data)
1470 }
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001471 } else if c.vers != VersionSSL30 {
1472 // In TLS, the Certificate message is required. In SSL
1473 // 3.0, the peer skips it when sending no certificates.
Adam Langley95c29f32014-06-20 12:00:00 -07001474 c.sendAlert(alertUnexpectedMessage)
1475 return unexpectedMessageError(certMsg, msg)
1476 }
Adam Langley95c29f32014-06-20 12:00:00 -07001477
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001478 if len(certificates) == 0 {
Adam Langley95c29f32014-06-20 12:00:00 -07001479 // The client didn't actually send a certificate
1480 switch config.ClientAuth {
1481 case RequireAnyClientCert, RequireAndVerifyClientCert:
1482 c.sendAlert(alertBadCertificate)
1483 return errors.New("tls: client didn't provide a certificate")
1484 }
1485 }
1486
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001487 pub, err = hs.processCertsFromClient(certificates)
Adam Langley95c29f32014-06-20 12:00:00 -07001488 if err != nil {
1489 return err
1490 }
1491
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001492 if ok {
1493 msg, err = c.readHandshake()
1494 if err != nil {
1495 return err
1496 }
Adam Langley95c29f32014-06-20 12:00:00 -07001497 }
1498 }
1499
1500 // Get client key exchange
1501 ckx, ok := msg.(*clientKeyExchangeMsg)
1502 if !ok {
1503 c.sendAlert(alertUnexpectedMessage)
1504 return unexpectedMessageError(ckx, msg)
1505 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001506 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001507
David Benjamine098ec22014-08-27 23:13:20 -04001508 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
1509 if err != nil {
1510 c.sendAlert(alertHandshakeFailure)
1511 return err
1512 }
Adam Langley75712922014-10-10 16:23:43 -07001513 if c.extendedMasterSecret {
1514 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1515 } else {
1516 if c.config.Bugs.RequireExtendedMasterSecret {
1517 return errors.New("tls: extended master secret required but not supported by peer")
1518 }
1519 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
1520 }
David Benjamine098ec22014-08-27 23:13:20 -04001521
Adam Langley95c29f32014-06-20 12:00:00 -07001522 // If we received a client cert in response to our certificate request message,
1523 // the client will send us a certificateVerifyMsg immediately after the
1524 // clientKeyExchangeMsg. This message is a digest of all preceding
1525 // handshake-layer messages that is signed using the private key corresponding
1526 // to the client's certificate. This allows us to verify that the client is in
1527 // possession of the private key of the certificate.
1528 if len(c.peerCertificates) > 0 {
1529 msg, err = c.readHandshake()
1530 if err != nil {
1531 return err
1532 }
1533 certVerify, ok := msg.(*certificateVerifyMsg)
1534 if !ok {
1535 c.sendAlert(alertUnexpectedMessage)
1536 return unexpectedMessageError(certVerify, msg)
1537 }
1538
David Benjaminde620d92014-07-18 15:03:41 -04001539 // Determine the signature type.
Nick Harper60edffd2016-06-21 15:19:24 -07001540 var sigAlg signatureAlgorithm
1541 if certVerify.hasSignatureAlgorithm {
1542 sigAlg = certVerify.signatureAlgorithm
Nick Harper60edffd2016-06-21 15:19:24 -07001543 c.peerSignatureAlgorithm = sigAlg
David Benjaminde620d92014-07-18 15:03:41 -04001544 }
1545
Nick Harper60edffd2016-06-21 15:19:24 -07001546 if c.vers > VersionSSL30 {
David Benjamin1fb125c2016-07-08 18:52:12 -07001547 err = verifyMessage(c.vers, pub, c.config, sigAlg, hs.finishedHash.buffer, certVerify.signature)
Nick Harper60edffd2016-06-21 15:19:24 -07001548 } else {
1549 // SSL 3.0's client certificate construction is
1550 // incompatible with signatureAlgorithm.
1551 rsaPub, ok := pub.(*rsa.PublicKey)
1552 if !ok {
1553 err = errors.New("unsupported key type for client certificate")
1554 } else {
1555 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
1556 err = rsa.VerifyPKCS1v15(rsaPub, crypto.MD5SHA1, digest, certVerify.signature)
David Benjaminde620d92014-07-18 15:03:41 -04001557 }
Adam Langley95c29f32014-06-20 12:00:00 -07001558 }
1559 if err != nil {
1560 c.sendAlert(alertBadCertificate)
1561 return errors.New("could not validate signature of connection nonces: " + err.Error())
1562 }
1563
David Benjamin83c0bc92014-08-04 01:23:53 -04001564 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001565 }
1566
David Benjamine098ec22014-08-27 23:13:20 -04001567 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001568
1569 return nil
1570}
1571
1572func (hs *serverHandshakeState) establishKeys() error {
1573 c := hs.c
1574
1575 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001576 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 -07001577
1578 var clientCipher, serverCipher interface{}
1579 var clientHash, serverHash macFunction
1580
1581 if hs.suite.aead == nil {
1582 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
1583 clientHash = hs.suite.mac(c.vers, clientMAC)
1584 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
1585 serverHash = hs.suite.mac(c.vers, serverMAC)
1586 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001587 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1588 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001589 }
1590
1591 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
1592 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
1593
1594 return nil
1595}
1596
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001597func (hs *serverHandshakeState) readFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001598 c := hs.c
1599
1600 c.readRecord(recordTypeChangeCipherSpec)
1601 if err := c.in.error(); err != nil {
1602 return err
1603 }
1604
Nick Harperb3d51be2016-07-01 11:43:18 -04001605 if hs.hello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001606 msg, err := c.readHandshake()
1607 if err != nil {
1608 return err
1609 }
1610 nextProto, ok := msg.(*nextProtoMsg)
1611 if !ok {
1612 c.sendAlert(alertUnexpectedMessage)
1613 return unexpectedMessageError(nextProto, msg)
1614 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001615 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001616 c.clientProtocol = nextProto.proto
1617 }
1618
Nick Harperb3d51be2016-07-01 11:43:18 -04001619 if hs.hello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001620 msg, err := c.readHandshake()
1621 if err != nil {
1622 return err
1623 }
David Benjamin24599a82016-06-30 18:56:53 -04001624 channelIDMsg, ok := msg.(*channelIDMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001625 if !ok {
1626 c.sendAlert(alertUnexpectedMessage)
David Benjamin24599a82016-06-30 18:56:53 -04001627 return unexpectedMessageError(channelIDMsg, msg)
David Benjamind30a9902014-08-24 01:44:23 -04001628 }
David Benjamind30a9902014-08-24 01:44:23 -04001629 var resumeHash []byte
1630 if isResume {
1631 resumeHash = hs.sessionState.handshakeHash
1632 }
Nick Harper60a85cb2016-09-23 16:25:11 -07001633 channelID, err := verifyChannelIDMessage(channelIDMsg, hs.finishedHash.hashForChannelID(resumeHash))
1634 if err != nil {
1635 return err
David Benjamind30a9902014-08-24 01:44:23 -04001636 }
1637 c.channelID = channelID
1638
David Benjamin24599a82016-06-30 18:56:53 -04001639 hs.writeClientHash(channelIDMsg.marshal())
David Benjamind30a9902014-08-24 01:44:23 -04001640 }
1641
Adam Langley95c29f32014-06-20 12:00:00 -07001642 msg, err := c.readHandshake()
1643 if err != nil {
1644 return err
1645 }
1646 clientFinished, ok := msg.(*finishedMsg)
1647 if !ok {
1648 c.sendAlert(alertUnexpectedMessage)
1649 return unexpectedMessageError(clientFinished, msg)
1650 }
1651
1652 verify := hs.finishedHash.clientSum(hs.masterSecret)
1653 if len(verify) != len(clientFinished.verifyData) ||
1654 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
1655 c.sendAlert(alertHandshakeFailure)
1656 return errors.New("tls: client's Finished message is incorrect")
1657 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001658 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001659 copy(out, clientFinished.verifyData)
Adam Langley95c29f32014-06-20 12:00:00 -07001660
David Benjamin83c0bc92014-08-04 01:23:53 -04001661 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001662 return nil
1663}
1664
1665func (hs *serverHandshakeState) sendSessionTicket() error {
Adam Langley95c29f32014-06-20 12:00:00 -07001666 c := hs.c
Adam Langley95c29f32014-06-20 12:00:00 -07001667 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -04001668 vers: c.vers,
1669 cipherSuite: hs.suite.id,
1670 masterSecret: hs.masterSecret,
1671 certificates: hs.certsFromClient,
Nick Harperc9846112016-10-17 15:05:35 -07001672 handshakeHash: hs.finishedHash.Sum(),
Adam Langley95c29f32014-06-20 12:00:00 -07001673 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001674
Nick Harperb3d51be2016-07-01 11:43:18 -04001675 if !hs.hello.extensions.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001676 if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
1677 c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
1678 }
1679 return nil
1680 }
1681
1682 m := new(newSessionTicketMsg)
1683
David Benjamindd6fed92015-10-23 17:41:12 -04001684 if !c.config.Bugs.SendEmptySessionTicket {
1685 var err error
1686 m.ticket, err = c.encryptTicket(&state)
1687 if err != nil {
1688 return err
1689 }
Adam Langley95c29f32014-06-20 12:00:00 -07001690 }
Adam Langley95c29f32014-06-20 12:00:00 -07001691
David Benjamin83c0bc92014-08-04 01:23:53 -04001692 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001693 c.writeRecord(recordTypeHandshake, m.marshal())
1694
1695 return nil
1696}
1697
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001698func (hs *serverHandshakeState) sendFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001699 c := hs.c
1700
David Benjamin86271ee2014-07-21 16:14:03 -04001701 finished := new(finishedMsg)
1702 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001703 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001704 if c.config.Bugs.BadFinished {
1705 finished.verifyData[0]++
1706 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001707 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001708 hs.finishedBytes = finished.marshal()
1709 hs.writeServerHash(hs.finishedBytes)
1710 postCCSBytes := hs.finishedBytes
David Benjamin86271ee2014-07-21 16:14:03 -04001711
1712 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
1713 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
1714 postCCSBytes = postCCSBytes[5:]
David Benjamin61672812016-07-14 23:10:43 -04001715 } else if c.config.Bugs.SendUnencryptedFinished {
1716 c.writeRecord(recordTypeHandshake, postCCSBytes)
1717 postCCSBytes = nil
David Benjamin86271ee2014-07-21 16:14:03 -04001718 }
David Benjamin582ba042016-07-07 12:33:25 -07001719 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001720
David Benjamina0e52232014-07-19 17:39:58 -04001721 if !c.config.Bugs.SkipChangeCipherSpec {
David Benjamin8411b242015-11-26 12:07:28 -05001722 ccs := []byte{1}
1723 if c.config.Bugs.BadChangeCipherSpec != nil {
1724 ccs = c.config.Bugs.BadChangeCipherSpec
1725 }
1726 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamina0e52232014-07-19 17:39:58 -04001727 }
Adam Langley95c29f32014-06-20 12:00:00 -07001728
David Benjamin4189bd92015-01-25 23:52:39 -05001729 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1730 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1731 }
David Benjamindc3da932015-03-12 15:09:02 -04001732 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1733 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1734 return errors.New("tls: simulating post-CCS alert")
1735 }
David Benjamin4189bd92015-01-25 23:52:39 -05001736
David Benjamin61672812016-07-14 23:10:43 -04001737 if !c.config.Bugs.SkipFinished && len(postCCSBytes) > 0 {
David Benjaminb80168e2015-02-08 18:30:14 -05001738 c.writeRecord(recordTypeHandshake, postCCSBytes)
David Benjamin02edcd02016-07-27 17:40:37 -04001739 if c.config.Bugs.SendExtraFinished {
1740 c.writeRecord(recordTypeHandshake, finished.marshal())
1741 }
1742
David Benjamin12d2c482016-07-24 10:56:51 -04001743 if !c.config.Bugs.PackHelloRequestWithFinished {
1744 // Defer flushing until renegotiation.
1745 c.flushHandshake()
1746 }
David Benjaminb3774b92015-01-31 17:16:01 -05001747 }
Adam Langley95c29f32014-06-20 12:00:00 -07001748
David Benjaminc565ebb2015-04-03 04:06:36 -04001749 c.cipherSuite = hs.suite
Adam Langley95c29f32014-06-20 12:00:00 -07001750
1751 return nil
1752}
1753
1754// processCertsFromClient takes a chain of client certificates either from a
1755// Certificates message or from a sessionState and verifies them. It returns
1756// the public key of the leaf certificate.
1757func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
1758 c := hs.c
1759
1760 hs.certsFromClient = certificates
1761 certs := make([]*x509.Certificate, len(certificates))
1762 var err error
1763 for i, asn1Data := range certificates {
1764 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
1765 c.sendAlert(alertBadCertificate)
1766 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
1767 }
1768 }
1769
1770 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
1771 opts := x509.VerifyOptions{
1772 Roots: c.config.ClientCAs,
1773 CurrentTime: c.config.time(),
1774 Intermediates: x509.NewCertPool(),
1775 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
1776 }
1777
1778 for _, cert := range certs[1:] {
1779 opts.Intermediates.AddCert(cert)
1780 }
1781
1782 chains, err := certs[0].Verify(opts)
1783 if err != nil {
1784 c.sendAlert(alertBadCertificate)
1785 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
1786 }
1787
1788 ok := false
1789 for _, ku := range certs[0].ExtKeyUsage {
1790 if ku == x509.ExtKeyUsageClientAuth {
1791 ok = true
1792 break
1793 }
1794 }
1795 if !ok {
1796 c.sendAlert(alertHandshakeFailure)
1797 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
1798 }
1799
1800 c.verifiedChains = chains
1801 }
1802
1803 if len(certs) > 0 {
1804 var pub crypto.PublicKey
1805 switch key := certs[0].PublicKey.(type) {
1806 case *ecdsa.PublicKey, *rsa.PublicKey:
1807 pub = key
1808 default:
1809 c.sendAlert(alertUnsupportedCertificate)
1810 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
1811 }
1812 c.peerCertificates = certs
1813 return pub, nil
1814 }
1815
1816 return nil, nil
1817}
1818
Nick Harper60a85cb2016-09-23 16:25:11 -07001819func verifyChannelIDMessage(channelIDMsg *channelIDMsg, channelIDHash []byte) (*ecdsa.PublicKey, error) {
1820 x := new(big.Int).SetBytes(channelIDMsg.channelID[0:32])
1821 y := new(big.Int).SetBytes(channelIDMsg.channelID[32:64])
1822 r := new(big.Int).SetBytes(channelIDMsg.channelID[64:96])
1823 s := new(big.Int).SetBytes(channelIDMsg.channelID[96:128])
1824 if !elliptic.P256().IsOnCurve(x, y) {
1825 return nil, errors.New("tls: invalid channel ID public key")
1826 }
1827 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
1828 if !ecdsa.Verify(channelID, channelIDHash, r, s) {
1829 return nil, errors.New("tls: invalid channel ID signature")
1830 }
1831 return channelID, nil
1832}
1833
David Benjamin83c0bc92014-08-04 01:23:53 -04001834func (hs *serverHandshakeState) writeServerHash(msg []byte) {
1835 // writeServerHash is called before writeRecord.
1836 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1837}
1838
1839func (hs *serverHandshakeState) writeClientHash(msg []byte) {
1840 // writeClientHash is called after readHandshake.
1841 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1842}
1843
1844func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
1845 if hs.c.isDTLS {
1846 // This is somewhat hacky. DTLS hashes a slightly different format.
1847 // First, the TLS header.
1848 hs.finishedHash.Write(msg[:4])
1849 // Then the sequence number and reassembled fragment offset (always 0).
1850 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1851 // Then the reassembled fragment (always equal to the message length).
1852 hs.finishedHash.Write(msg[1:4])
1853 // And then the message body.
1854 hs.finishedHash.Write(msg[4:])
1855 } else {
1856 hs.finishedHash.Write(msg)
1857 }
1858}
1859
Adam Langley95c29f32014-06-20 12:00:00 -07001860// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
1861// is acceptable to use.
Steven Valdez803c77a2016-09-06 14:13:43 -04001862func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
Adam Langley95c29f32014-06-20 12:00:00 -07001863 for _, supported := range supportedCipherSuites {
1864 if id == supported {
1865 var candidate *cipherSuite
1866
1867 for _, s := range cipherSuites {
1868 if s.id == id {
1869 candidate = s
1870 break
1871 }
1872 }
1873 if candidate == nil {
1874 continue
1875 }
Steven Valdez803c77a2016-09-06 14:13:43 -04001876
Adam Langley95c29f32014-06-20 12:00:00 -07001877 // Don't select a ciphersuite which we can't
1878 // support for this client.
Steven Valdez803c77a2016-09-06 14:13:43 -04001879 if version >= VersionTLS13 || candidate.flags&suiteTLS13 != 0 {
1880 if version < VersionTLS13 || candidate.flags&suiteTLS13 == 0 {
1881 continue
1882 }
1883 return candidate
David Benjamin5ecb88b2016-10-04 17:51:35 -04001884 }
1885 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
1886 continue
1887 }
1888 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
1889 continue
1890 }
1891 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
1892 continue
1893 }
David Benjamin5ecb88b2016-10-04 17:51:35 -04001894 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
1895 continue
David Benjamin83c0bc92014-08-04 01:23:53 -04001896 }
Adam Langley95c29f32014-06-20 12:00:00 -07001897 return candidate
1898 }
1899 }
1900
1901 return nil
1902}
David Benjaminf93995b2015-11-05 18:23:20 -05001903
1904func isTLS12Cipher(id uint16) bool {
1905 for _, cipher := range cipherSuites {
1906 if cipher.id != id {
1907 continue
1908 }
1909 return cipher.flags&suiteTLS12 != 0
1910 }
1911 // Unknown cipher.
1912 return false
1913}
David Benjamin65ac9972016-09-02 21:35:25 -04001914
1915func isGREASEValue(val uint16) bool {
David Benjamin3c6a1ea2016-09-26 18:30:05 -04001916 return val&0x0f0f == 0x0a0a && val&0xff == val>>8
David Benjamin65ac9972016-09-02 21:35:25 -04001917}
Steven Valdeza833c352016-11-01 13:39:36 -04001918
1919func verifyPSKBinder(clientHello *clientHelloMsg, sessionState *sessionState, binderToVerify, transcript []byte) error {
1920 binderLen := 2
1921 for _, binder := range clientHello.pskBinders {
1922 binderLen += 1 + len(binder)
1923 }
1924
1925 truncatedHello := clientHello.marshal()
1926 truncatedHello = truncatedHello[:len(truncatedHello)-binderLen]
1927 pskCipherSuite := cipherSuiteFromID(sessionState.cipherSuite)
1928 if pskCipherSuite == nil {
1929 return errors.New("tls: Unknown cipher suite for PSK in session")
1930 }
1931
1932 binder := computePSKBinder(sessionState.masterSecret, resumptionPSKBinderLabel, pskCipherSuite, transcript, truncatedHello)
1933 if !bytes.Equal(binder, binderToVerify) {
1934 return errors.New("tls: PSK binder does not verify")
1935 }
1936
1937 return nil
1938}