blob: 012c8364746a51cd6cabb1ebfec5ad46becc3f6f [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() {
87 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
88 c.flushHandshake()
89 }); err != nil {
90 return err
91 }
92 if err := hs.readFinished(nil, isResume); err != nil {
93 return err
94 }
95 c.didResume = true
96 } else {
97 // The client didn't include a session ticket, or it wasn't
98 // valid so we do a full handshake.
99 if err := hs.doFullHandshake(); err != nil {
100 return err
101 }
102 if err := hs.establishKeys(); err != nil {
103 return err
104 }
105 if err := hs.readFinished(c.firstFinished[:], isResume); err != nil {
106 return err
107 }
108 if c.config.Bugs.AlertBeforeFalseStartTest != 0 {
109 c.sendAlert(c.config.Bugs.AlertBeforeFalseStartTest)
110 }
111 if c.config.Bugs.ExpectFalseStart {
112 if err := c.readRecord(recordTypeApplicationData); err != nil {
113 return fmt.Errorf("tls: peer did not false start: %s", err)
114 }
115 }
David Benjaminbed9aae2014-08-07 19:13:38 -0400116 if err := hs.sendSessionTicket(); err != nil {
117 return err
118 }
Nick Harper728eed82016-07-07 17:36:52 -0700119 if err := hs.sendFinished(nil); err != nil {
120 return err
David Benjamine58c4f52014-08-24 03:47:07 -0400121 }
122 }
David Benjamin97a0a082016-07-13 17:57:35 -0400123
124 c.exporterSecret = hs.masterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700125 }
126 c.handshakeComplete = true
David Benjaminc565ebb2015-04-03 04:06:36 -0400127 copy(c.clientRandom[:], hs.clientHello.random)
128 copy(c.serverRandom[:], hs.hello.random)
Adam Langley95c29f32014-06-20 12:00:00 -0700129
130 return nil
131}
132
David Benjaminf25dda92016-07-04 10:05:26 -0700133// readClientHello reads a ClientHello message from the client and determines
134// the protocol version.
135func (hs *serverHandshakeState) readClientHello() error {
Adam Langley95c29f32014-06-20 12:00:00 -0700136 config := hs.c.config
137 c := hs.c
138
David Benjamin83f90402015-01-27 01:09:43 -0500139 if err := c.simulatePacketLoss(nil); err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700140 return err
David Benjamin83f90402015-01-27 01:09:43 -0500141 }
Adam Langley95c29f32014-06-20 12:00:00 -0700142 msg, err := c.readHandshake()
143 if err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700144 return err
Adam Langley95c29f32014-06-20 12:00:00 -0700145 }
146 var ok bool
147 hs.clientHello, ok = msg.(*clientHelloMsg)
148 if !ok {
149 c.sendAlert(alertUnexpectedMessage)
David Benjaminf25dda92016-07-04 10:05:26 -0700150 return unexpectedMessageError(hs.clientHello, msg)
Adam Langley95c29f32014-06-20 12:00:00 -0700151 }
Adam Langley33ad2b52015-07-20 17:43:53 -0700152 if size := config.Bugs.RequireClientHelloSize; size != 0 && len(hs.clientHello.raw) != size {
David Benjaminf25dda92016-07-04 10:05:26 -0700153 return fmt.Errorf("tls: ClientHello record size is %d, but expected %d", len(hs.clientHello.raw), size)
Feng Lu41aa3252014-11-21 22:47:56 -0800154 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400155
156 if c.isDTLS && !config.Bugs.SkipHelloVerifyRequest {
David Benjamin8bc38f52014-08-16 12:07:27 -0400157 // Per RFC 6347, the version field in HelloVerifyRequest SHOULD
158 // be always DTLS 1.0
David Benjamin83c0bc92014-08-04 01:23:53 -0400159 helloVerifyRequest := &helloVerifyRequestMsg{
David Benjamin8bc38f52014-08-16 12:07:27 -0400160 vers: VersionTLS10,
David Benjamin83c0bc92014-08-04 01:23:53 -0400161 cookie: make([]byte, 32),
162 }
163 if _, err := io.ReadFull(c.config.rand(), helloVerifyRequest.cookie); err != nil {
164 c.sendAlert(alertInternalError)
David Benjaminf25dda92016-07-04 10:05:26 -0700165 return errors.New("dtls: short read from Rand: " + err.Error())
David Benjamin83c0bc92014-08-04 01:23:53 -0400166 }
167 c.writeRecord(recordTypeHandshake, helloVerifyRequest.marshal())
David Benjamin582ba042016-07-07 12:33:25 -0700168 c.flushHandshake()
David Benjamin83c0bc92014-08-04 01:23:53 -0400169
David Benjamin83f90402015-01-27 01:09:43 -0500170 if err := c.simulatePacketLoss(nil); err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700171 return err
David Benjamin83f90402015-01-27 01:09:43 -0500172 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400173 msg, err := c.readHandshake()
174 if err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700175 return err
David Benjamin83c0bc92014-08-04 01:23:53 -0400176 }
177 newClientHello, ok := msg.(*clientHelloMsg)
178 if !ok {
179 c.sendAlert(alertUnexpectedMessage)
David Benjaminf25dda92016-07-04 10:05:26 -0700180 return unexpectedMessageError(hs.clientHello, msg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400181 }
182 if !bytes.Equal(newClientHello.cookie, helloVerifyRequest.cookie) {
David Benjaminf25dda92016-07-04 10:05:26 -0700183 return errors.New("dtls: invalid cookie")
David Benjamin83c0bc92014-08-04 01:23:53 -0400184 }
David Benjaminf2fedef2014-08-16 01:37:34 -0400185
186 // Apart from the cookie, the two ClientHellos must
187 // match. Note that clientHello.equal compares the
188 // serialization, so we make a copy.
189 oldClientHelloCopy := *hs.clientHello
190 oldClientHelloCopy.raw = nil
191 oldClientHelloCopy.cookie = nil
192 newClientHelloCopy := *newClientHello
193 newClientHelloCopy.raw = nil
194 newClientHelloCopy.cookie = nil
195 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
David Benjaminf25dda92016-07-04 10:05:26 -0700196 return errors.New("dtls: retransmitted ClientHello does not match")
David Benjamin83c0bc92014-08-04 01:23:53 -0400197 }
198 hs.clientHello = newClientHello
199 }
200
David Benjaminc44b1df2014-11-23 12:11:01 -0500201 if config.Bugs.RequireSameRenegoClientVersion && c.clientVersion != 0 {
202 if c.clientVersion != hs.clientHello.vers {
David Benjaminf25dda92016-07-04 10:05:26 -0700203 return fmt.Errorf("tls: client offered different version on renego")
David Benjaminc44b1df2014-11-23 12:11:01 -0500204 }
205 }
206 c.clientVersion = hs.clientHello.vers
207
David Benjamin6ae7f072015-01-26 10:22:13 -0500208 // Reject < 1.2 ClientHellos with signature_algorithms.
Nick Harper60edffd2016-06-21 15:19:24 -0700209 if c.clientVersion < VersionTLS12 && len(hs.clientHello.signatureAlgorithms) > 0 {
David Benjaminf25dda92016-07-04 10:05:26 -0700210 return fmt.Errorf("tls: client included signature_algorithms before TLS 1.2")
David Benjamin72dc7832015-03-16 17:49:43 -0400211 }
David Benjamin6ae7f072015-01-26 10:22:13 -0500212
David Benjaminf93995b2015-11-05 18:23:20 -0500213 // Check the client cipher list is consistent with the version.
214 if hs.clientHello.vers < VersionTLS12 {
215 for _, id := range hs.clientHello.cipherSuites {
216 if isTLS12Cipher(id) {
David Benjaminf25dda92016-07-04 10:05:26 -0700217 return fmt.Errorf("tls: client offered TLS 1.2 cipher before TLS 1.2")
David Benjaminf93995b2015-11-05 18:23:20 -0500218 }
219 }
220 }
221
David Benjamin1f61f0d2016-07-10 12:20:35 -0400222 if config.Bugs.NegotiateVersion != 0 {
223 c.vers = config.Bugs.NegotiateVersion
224 } else {
225 c.vers, ok = config.mutualVersion(hs.clientHello.vers, c.isDTLS)
226 if !ok {
227 c.sendAlert(alertProtocolVersion)
228 return fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
229 }
David Benjamin8bc38f52014-08-16 12:07:27 -0400230 }
Adam Langley95c29f32014-06-20 12:00:00 -0700231 c.haveVers = true
232
David Benjaminf25dda92016-07-04 10:05:26 -0700233 var scsvFound bool
234 for _, cipherSuite := range hs.clientHello.cipherSuites {
235 if cipherSuite == fallbackSCSV {
236 scsvFound = true
237 break
238 }
239 }
240
241 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
242 return errors.New("tls: no fallback SCSV found when expected")
243 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
244 return errors.New("tls: fallback SCSV found when not expected")
245 }
246
247 if config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
David Benjamin7a41d372016-07-09 11:21:54 -0700248 hs.clientHello.signatureAlgorithms = config.signSignatureAlgorithms()
David Benjaminf25dda92016-07-04 10:05:26 -0700249 }
250 if config.Bugs.IgnorePeerCurvePreferences {
251 hs.clientHello.supportedCurves = config.curvePreferences()
252 }
253 if config.Bugs.IgnorePeerCipherPreferences {
254 hs.clientHello.cipherSuites = config.cipherSuites()
255 }
256
257 return nil
258}
259
Nick Harper728eed82016-07-07 17:36:52 -0700260func (hs *serverHandshakeState) doTLS13Handshake() error {
261 c := hs.c
262 config := c.config
263
264 hs.hello = &serverHelloMsg{
265 isDTLS: c.isDTLS,
266 vers: c.vers,
267 }
268
Steven Valdez5440fe02016-07-18 12:40:30 -0400269 if config.Bugs.SendServerHelloVersion != 0 {
270 hs.hello.vers = config.Bugs.SendServerHelloVersion
271 }
272
Nick Harper728eed82016-07-07 17:36:52 -0700273 hs.hello.random = make([]byte, 32)
274 if _, err := io.ReadFull(config.rand(), hs.hello.random); err != nil {
275 c.sendAlert(alertInternalError)
276 return err
277 }
278
279 // TLS 1.3 forbids clients from advertising any non-null compression.
280 if len(hs.clientHello.compressionMethods) != 1 || hs.clientHello.compressionMethods[0] != compressionNone {
281 return errors.New("tls: client sent compression method other than null for TLS 1.3")
282 }
283
284 // Prepare an EncryptedExtensions message, but do not send it yet.
285 encryptedExtensions := new(encryptedExtensionsMsg)
Steven Valdez143e8b32016-07-11 13:19:03 -0400286 encryptedExtensions.empty = config.Bugs.EmptyEncryptedExtensions
Nick Harper728eed82016-07-07 17:36:52 -0700287 if err := hs.processClientExtensions(&encryptedExtensions.extensions); err != nil {
288 return err
289 }
290
291 supportedCurve := false
292 var selectedCurve CurveID
293 preferredCurves := config.curvePreferences()
294Curves:
295 for _, curve := range hs.clientHello.supportedCurves {
296 for _, supported := range preferredCurves {
297 if supported == curve {
298 supportedCurve = true
299 selectedCurve = curve
300 break Curves
301 }
302 }
303 }
304
305 _, ecdsaOk := hs.cert.PrivateKey.(*ecdsa.PrivateKey)
306
307 // TODO(davidben): Implement PSK support.
308 pskOk := false
309
310 // Select the cipher suite.
311 var preferenceList, supportedList []uint16
312 if config.PreferServerCipherSuites {
313 preferenceList = config.cipherSuites()
314 supportedList = hs.clientHello.cipherSuites
315 } else {
316 preferenceList = hs.clientHello.cipherSuites
317 supportedList = config.cipherSuites()
318 }
319
320 for _, id := range preferenceList {
321 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, supportedCurve, ecdsaOk, pskOk); hs.suite != nil {
322 break
323 }
324 }
325
326 if hs.suite == nil {
327 c.sendAlert(alertHandshakeFailure)
328 return errors.New("tls: no cipher suite supported by both client and server")
329 }
330
331 hs.hello.cipherSuite = hs.suite.id
Steven Valdez0ee2e112016-07-15 06:51:15 -0400332 if c.config.Bugs.SendCipherSuite != 0 {
333 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
334 }
335
Nick Harper728eed82016-07-07 17:36:52 -0700336 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
337 hs.finishedHash.discardHandshakeBuffer()
338 hs.writeClientHash(hs.clientHello.marshal())
339
340 // Resolve PSK and compute the early secret.
David Benjaminc87ebde2016-07-13 17:26:02 -0400341 // TODO(davidben): Implement PSK in TLS 1.3.
342 psk := hs.finishedHash.zeroSecret()
343 hs.finishedHash.setResumptionContext(hs.finishedHash.zeroSecret())
Nick Harper728eed82016-07-07 17:36:52 -0700344
345 earlySecret := hs.finishedHash.extractKey(hs.finishedHash.zeroSecret(), psk)
346
347 // Resolve ECDHE and compute the handshake secret.
348 var ecdheSecret []byte
Steven Valdez143e8b32016-07-11 13:19:03 -0400349 if hs.suite.flags&suiteECDHE != 0 && !config.Bugs.MissingKeyShare {
Nick Harper728eed82016-07-07 17:36:52 -0700350 // Look for the key share corresponding to our selected curve.
351 var selectedKeyShare *keyShareEntry
352 for i := range hs.clientHello.keyShares {
353 if hs.clientHello.keyShares[i].group == selectedCurve {
354 selectedKeyShare = &hs.clientHello.keyShares[i]
355 break
356 }
357 }
358
Steven Valdez5440fe02016-07-18 12:40:30 -0400359 sendHelloRetryRequest := selectedKeyShare == nil
360 if config.Bugs.UnnecessaryHelloRetryRequest {
361 sendHelloRetryRequest = true
362 }
363 if config.Bugs.SkipHelloRetryRequest {
364 sendHelloRetryRequest = false
365 }
366 if sendHelloRetryRequest {
367 firstTime := true
368 ResendHelloRetryRequest:
Nick Harperdcfbc672016-07-16 17:47:31 +0200369 // Send HelloRetryRequest.
370 helloRetryRequestMsg := helloRetryRequestMsg{
371 vers: c.vers,
372 cipherSuite: hs.hello.cipherSuite,
373 selectedGroup: selectedCurve,
374 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400375 if config.Bugs.SendHelloRetryRequestCurve != 0 {
376 helloRetryRequestMsg.selectedGroup = config.Bugs.SendHelloRetryRequestCurve
377 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200378 hs.writeServerHash(helloRetryRequestMsg.marshal())
379 c.writeRecord(recordTypeHandshake, helloRetryRequestMsg.marshal())
380
381 // Read new ClientHello.
382 newMsg, err := c.readHandshake()
383 if err != nil {
384 return err
385 }
386 newClientHello, ok := newMsg.(*clientHelloMsg)
387 if !ok {
388 c.sendAlert(alertUnexpectedMessage)
389 return unexpectedMessageError(newClientHello, newMsg)
390 }
391 hs.writeClientHash(newClientHello.marshal())
392
393 // Check that the new ClientHello matches the old ClientHello, except for
394 // the addition of the new KeyShareEntry at the end of the list, and
395 // removing the EarlyDataIndication extension (if present).
396 newKeyShares := newClientHello.keyShares
397 if len(newKeyShares) == 0 || newKeyShares[len(newKeyShares)-1].group != selectedCurve {
398 return errors.New("tls: KeyShare from HelloRetryRequest not present in new ClientHello")
399 }
400 oldClientHelloCopy := *hs.clientHello
401 oldClientHelloCopy.raw = nil
402 oldClientHelloCopy.hasEarlyData = false
403 oldClientHelloCopy.earlyDataContext = nil
404 newClientHelloCopy := *newClientHello
405 newClientHelloCopy.raw = nil
406 newClientHelloCopy.keyShares = newKeyShares[:len(newKeyShares)-1]
407 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
408 return errors.New("tls: new ClientHello does not match")
409 }
410
Steven Valdez5440fe02016-07-18 12:40:30 -0400411 if firstTime && config.Bugs.SecondHelloRetryRequest {
412 firstTime = false
413 goto ResendHelloRetryRequest
414 }
415
Nick Harperdcfbc672016-07-16 17:47:31 +0200416 selectedKeyShare = &newKeyShares[len(newKeyShares)-1]
Nick Harper728eed82016-07-07 17:36:52 -0700417 }
418
419 // Once a curve has been selected and a key share identified,
420 // the server needs to generate a public value and send it in
421 // the ServerHello.
Steven Valdez5440fe02016-07-18 12:40:30 -0400422 curve, ok := curveForCurveID(selectedCurve)
Nick Harper728eed82016-07-07 17:36:52 -0700423 if !ok {
424 panic("tls: server failed to look up curve ID")
425 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400426 c.curveID = selectedCurve
427
428 var peerKey []byte
429 if config.Bugs.SkipHelloRetryRequest {
430 // If skipping HelloRetryRequest, use a random key to
431 // avoid crashing.
432 curve2, _ := curveForCurveID(selectedCurve)
433 var err error
434 peerKey, err = curve2.offer(config.rand())
435 if err != nil {
436 return err
437 }
438 } else {
439 peerKey = selectedKeyShare.keyExchange
440 }
441
Nick Harper728eed82016-07-07 17:36:52 -0700442 var publicKey []byte
443 var err error
Steven Valdez5440fe02016-07-18 12:40:30 -0400444 publicKey, ecdheSecret, err = curve.accept(config.rand(), peerKey)
Nick Harper728eed82016-07-07 17:36:52 -0700445 if err != nil {
446 c.sendAlert(alertHandshakeFailure)
447 return err
448 }
449 hs.hello.hasKeyShare = true
Steven Valdez0ee2e112016-07-15 06:51:15 -0400450
Steven Valdez5440fe02016-07-18 12:40:30 -0400451 curveID := selectedCurve
Steven Valdez0ee2e112016-07-15 06:51:15 -0400452 if c.config.Bugs.SendCurve != 0 {
453 curveID = config.Bugs.SendCurve
454 }
455 if c.config.Bugs.InvalidECDHPoint {
456 publicKey[0] ^= 0xff
457 }
458
Nick Harper728eed82016-07-07 17:36:52 -0700459 hs.hello.keyShare = keyShareEntry{
Steven Valdez0ee2e112016-07-15 06:51:15 -0400460 group: curveID,
Nick Harper728eed82016-07-07 17:36:52 -0700461 keyExchange: publicKey,
462 }
Steven Valdez143e8b32016-07-11 13:19:03 -0400463
464 if config.Bugs.EncryptedExtensionsWithKeyShare {
465 encryptedExtensions.extensions.hasKeyShare = true
466 encryptedExtensions.extensions.keyShare = keyShareEntry{
467 group: curveID,
468 keyExchange: publicKey,
469 }
470 }
Nick Harper728eed82016-07-07 17:36:52 -0700471 } else {
472 ecdheSecret = hs.finishedHash.zeroSecret()
473 }
474
475 // Send unencrypted ServerHello.
476 hs.writeServerHash(hs.hello.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400477 if config.Bugs.PartialEncryptedExtensionsWithServerHello {
478 helloBytes := hs.hello.marshal()
479 toWrite := make([]byte, 0, len(helloBytes)+1)
480 toWrite = append(toWrite, helloBytes...)
481 toWrite = append(toWrite, typeEncryptedExtensions)
482 c.writeRecord(recordTypeHandshake, toWrite)
483 } else {
484 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
485 }
Nick Harper728eed82016-07-07 17:36:52 -0700486 c.flushHandshake()
487
488 // Compute the handshake secret.
489 handshakeSecret := hs.finishedHash.extractKey(earlySecret, ecdheSecret)
490
491 // Switch to handshake traffic keys.
492 handshakeTrafficSecret := hs.finishedHash.deriveSecret(handshakeSecret, handshakeTrafficLabel)
David Benjamin21c00282016-07-18 21:56:23 +0200493 c.out.useTrafficSecret(c.vers, hs.suite, handshakeTrafficSecret, handshakePhase, serverWrite)
494 c.in.useTrafficSecret(c.vers, hs.suite, handshakeTrafficSecret, handshakePhase, clientWrite)
Nick Harper728eed82016-07-07 17:36:52 -0700495
David Benjamin615119a2016-07-06 19:22:55 -0700496 if hs.suite.flags&suitePSK != 0 {
David Benjaminc87ebde2016-07-13 17:26:02 -0400497 return errors.New("tls: PSK ciphers not implemented for TLS 1.3")
498 } else {
David Benjamin615119a2016-07-06 19:22:55 -0700499 if hs.clientHello.ocspStapling {
500 encryptedExtensions.extensions.ocspResponse = hs.cert.OCSPStaple
501 }
502 if hs.clientHello.sctListSupported {
503 encryptedExtensions.extensions.sctList = hs.cert.SignedCertificateTimestampList
504 }
505 }
506
Nick Harper728eed82016-07-07 17:36:52 -0700507 // Send EncryptedExtensions.
508 hs.writeServerHash(encryptedExtensions.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400509 if config.Bugs.PartialEncryptedExtensionsWithServerHello {
510 // The first byte has already been sent.
511 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()[1:])
512 } else {
513 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal())
514 }
Nick Harper728eed82016-07-07 17:36:52 -0700515
516 if hs.suite.flags&suitePSK == 0 {
517 if config.ClientAuth >= RequestClientCert {
David Benjamin8d343b42016-07-09 14:26:01 -0700518 // Request a client certificate
519 certReq := &certificateRequestMsg{
520 hasSignatureAlgorithm: true,
521 hasRequestContext: true,
522 }
523 if !config.Bugs.NoSignatureAlgorithms {
David Benjaminf74ec792016-07-13 21:18:49 -0400524 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin8d343b42016-07-09 14:26:01 -0700525 }
526
527 // An empty list of certificateAuthorities signals to
528 // the client that it may send any certificate in response
529 // to our request. When we know the CAs we trust, then
530 // we can send them down, so that the client can choose
531 // an appropriate certificate to give to us.
532 if config.ClientCAs != nil {
533 certReq.certificateAuthorities = config.ClientCAs.Subjects()
534 }
535 hs.writeServerHash(certReq.marshal())
536 c.writeRecord(recordTypeHandshake, certReq.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700537 }
538
539 certMsg := &certificateMsg{
540 hasRequestContext: true,
541 }
542 if !config.Bugs.EmptyCertificateList {
543 certMsg.certificates = hs.cert.Certificate
544 }
David Benjamin1edae6b2016-07-13 16:58:23 -0400545 certMsgBytes := certMsg.marshal()
David Benjamin1edae6b2016-07-13 16:58:23 -0400546 hs.writeServerHash(certMsgBytes)
547 c.writeRecord(recordTypeHandshake, certMsgBytes)
Nick Harper728eed82016-07-07 17:36:52 -0700548
549 certVerify := &certificateVerifyMsg{
550 hasSignatureAlgorithm: true,
551 }
552
553 // Determine the hash to sign.
554 privKey := hs.cert.PrivateKey
555
556 var err error
557 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, config, hs.clientHello.signatureAlgorithms)
558 if err != nil {
559 c.sendAlert(alertInternalError)
560 return err
561 }
562
563 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
564 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
565 if err != nil {
566 c.sendAlert(alertInternalError)
567 return err
568 }
569
Steven Valdez0ee2e112016-07-15 06:51:15 -0400570 if config.Bugs.SendSignatureAlgorithm != 0 {
571 certVerify.signatureAlgorithm = config.Bugs.SendSignatureAlgorithm
572 }
573
Nick Harper728eed82016-07-07 17:36:52 -0700574 hs.writeServerHash(certVerify.marshal())
575 c.writeRecord(recordTypeHandshake, certVerify.marshal())
576 }
577
578 finished := new(finishedMsg)
579 finished.verifyData = hs.finishedHash.serverSum(handshakeTrafficSecret)
580 if config.Bugs.BadFinished {
581 finished.verifyData[0]++
582 }
583 hs.writeServerHash(finished.marshal())
584 c.writeRecord(recordTypeHandshake, finished.marshal())
585 c.flushHandshake()
586
587 // The various secrets do not incorporate the client's final leg, so
588 // derive them now before updating the handshake context.
589 masterSecret := hs.finishedHash.extractKey(handshakeSecret, hs.finishedHash.zeroSecret())
590 trafficSecret := hs.finishedHash.deriveSecret(masterSecret, applicationTrafficLabel)
591
David Benjamin2aad4062016-07-14 23:15:40 -0400592 // Switch to application data keys on write. In particular, any alerts
593 // from the client certificate are sent over these keys.
David Benjamin21c00282016-07-18 21:56:23 +0200594 c.out.useTrafficSecret(c.vers, hs.suite, trafficSecret, applicationPhase, serverWrite)
David Benjamin2aad4062016-07-14 23:15:40 -0400595
Nick Harper728eed82016-07-07 17:36:52 -0700596 // If we requested a client certificate, then the client must send a
597 // certificate message, even if it's empty.
598 if config.ClientAuth >= RequestClientCert {
David Benjamin8d343b42016-07-09 14:26:01 -0700599 msg, err := c.readHandshake()
600 if err != nil {
601 return err
602 }
603
604 certMsg, ok := msg.(*certificateMsg)
605 if !ok {
606 c.sendAlert(alertUnexpectedMessage)
607 return unexpectedMessageError(certMsg, msg)
608 }
609 hs.writeClientHash(certMsg.marshal())
610
611 if len(certMsg.certificates) == 0 {
612 // The client didn't actually send a certificate
613 switch config.ClientAuth {
614 case RequireAnyClientCert, RequireAndVerifyClientCert:
615 c.sendAlert(alertBadCertificate)
616 return errors.New("tls: client didn't provide a certificate")
617 }
618 }
619
620 pub, err := hs.processCertsFromClient(certMsg.certificates)
621 if err != nil {
622 return err
623 }
624
625 if len(c.peerCertificates) > 0 {
626 msg, err = c.readHandshake()
627 if err != nil {
628 return err
629 }
630
631 certVerify, ok := msg.(*certificateVerifyMsg)
632 if !ok {
633 c.sendAlert(alertUnexpectedMessage)
634 return unexpectedMessageError(certVerify, msg)
635 }
636
David Benjaminf74ec792016-07-13 21:18:49 -0400637 c.peerSignatureAlgorithm = certVerify.signatureAlgorithm
David Benjamin8d343b42016-07-09 14:26:01 -0700638 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
639 if err := verifyMessage(c.vers, pub, config, certVerify.signatureAlgorithm, input, certVerify.signature); err != nil {
640 c.sendAlert(alertBadCertificate)
641 return err
642 }
643 hs.writeClientHash(certVerify.marshal())
644 }
Nick Harper728eed82016-07-07 17:36:52 -0700645 }
646
647 // Read the client Finished message.
648 msg, err := c.readHandshake()
649 if err != nil {
650 return err
651 }
652 clientFinished, ok := msg.(*finishedMsg)
653 if !ok {
654 c.sendAlert(alertUnexpectedMessage)
655 return unexpectedMessageError(clientFinished, msg)
656 }
657
658 verify := hs.finishedHash.clientSum(handshakeTrafficSecret)
659 if len(verify) != len(clientFinished.verifyData) ||
660 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
661 c.sendAlert(alertHandshakeFailure)
662 return errors.New("tls: client's Finished message was incorrect")
663 }
David Benjamin97a0a082016-07-13 17:57:35 -0400664 hs.writeClientHash(clientFinished.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700665
David Benjamin2aad4062016-07-14 23:15:40 -0400666 // Switch to application data keys on read.
David Benjamin21c00282016-07-18 21:56:23 +0200667 c.in.useTrafficSecret(c.vers, hs.suite, trafficSecret, applicationPhase, clientWrite)
Nick Harper728eed82016-07-07 17:36:52 -0700668
Nick Harper728eed82016-07-07 17:36:52 -0700669 c.cipherSuite = hs.suite
David Benjamin97a0a082016-07-13 17:57:35 -0400670 c.exporterSecret = hs.finishedHash.deriveSecret(masterSecret, exporterLabel)
David Benjamin58104882016-07-18 01:25:41 +0200671 c.resumptionSecret = hs.finishedHash.deriveSecret(masterSecret, resumptionLabel)
672
673 // TODO(davidben): Allow configuring the number of tickets sent for
674 // testing.
675 if !c.config.SessionTicketsDisabled {
676 ticketCount := 2
677 for i := 0; i < ticketCount; i++ {
678 c.SendNewSessionTicket()
679 }
680 }
Nick Harper728eed82016-07-07 17:36:52 -0700681 return nil
682}
683
David Benjaminf25dda92016-07-04 10:05:26 -0700684// processClientHello processes the ClientHello message from the client and
685// decides whether we will perform session resumption.
686func (hs *serverHandshakeState) processClientHello() (isResume bool, err error) {
687 config := hs.c.config
688 c := hs.c
689
690 hs.hello = &serverHelloMsg{
691 isDTLS: c.isDTLS,
692 vers: c.vers,
693 compressionMethod: compressionNone,
694 }
695
Steven Valdez5440fe02016-07-18 12:40:30 -0400696 if config.Bugs.SendServerHelloVersion != 0 {
697 hs.hello.vers = config.Bugs.SendServerHelloVersion
698 }
699
David Benjaminf25dda92016-07-04 10:05:26 -0700700 hs.hello.random = make([]byte, 32)
701 _, err = io.ReadFull(config.rand(), hs.hello.random)
702 if err != nil {
703 c.sendAlert(alertInternalError)
704 return false, err
705 }
David Benjamin1f61f0d2016-07-10 12:20:35 -0400706 // Signal downgrades in the server random, per draft-ietf-tls-tls13-14,
707 // section 6.3.1.2.
Nick Harper85f20c22016-07-04 10:11:59 -0700708 if c.vers <= VersionTLS12 && config.maxVersion(c.isDTLS) >= VersionTLS13 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400709 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS13)
Nick Harper85f20c22016-07-04 10:11:59 -0700710 }
711 if c.vers <= VersionTLS11 && config.maxVersion(c.isDTLS) == VersionTLS12 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400712 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS12)
Nick Harper85f20c22016-07-04 10:11:59 -0700713 }
David Benjaminf25dda92016-07-04 10:05:26 -0700714
715 foundCompression := false
716 // We only support null compression, so check that the client offered it.
717 for _, compression := range hs.clientHello.compressionMethods {
718 if compression == compressionNone {
719 foundCompression = true
720 break
721 }
722 }
723
724 if !foundCompression {
725 c.sendAlert(alertHandshakeFailure)
726 return false, errors.New("tls: client does not support uncompressed connections")
727 }
David Benjamin7d79f832016-07-04 09:20:45 -0700728
729 if err := hs.processClientExtensions(&hs.hello.extensions); err != nil {
730 return false, err
Adam Langley09505632015-07-30 18:10:13 -0700731 }
Adam Langley95c29f32014-06-20 12:00:00 -0700732
733 supportedCurve := false
734 preferredCurves := config.curvePreferences()
735Curves:
736 for _, curve := range hs.clientHello.supportedCurves {
737 for _, supported := range preferredCurves {
738 if supported == curve {
739 supportedCurve = true
740 break Curves
741 }
742 }
743 }
744
745 supportedPointFormat := false
746 for _, pointFormat := range hs.clientHello.supportedPoints {
747 if pointFormat == pointFormatUncompressed {
748 supportedPointFormat = true
749 break
750 }
751 }
752 hs.ellipticOk = supportedCurve && supportedPointFormat
753
Adam Langley95c29f32014-06-20 12:00:00 -0700754 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
755
David Benjamin4b27d9f2015-05-12 22:42:52 -0400756 // For test purposes, check that the peer never offers a session when
757 // renegotiating.
758 if c.cipherSuite != nil && len(hs.clientHello.sessionId) > 0 && c.config.Bugs.FailIfResumeOnRenego {
759 return false, errors.New("tls: offered resumption on renegotiation")
760 }
761
David Benjamindd6fed92015-10-23 17:41:12 -0400762 if c.config.Bugs.FailIfSessionOffered && (len(hs.clientHello.sessionTicket) > 0 || len(hs.clientHello.sessionId) > 0) {
763 return false, errors.New("tls: client offered a session ticket or ID")
764 }
765
Adam Langley95c29f32014-06-20 12:00:00 -0700766 if hs.checkForResumption() {
767 return true, nil
768 }
769
Adam Langley95c29f32014-06-20 12:00:00 -0700770 var preferenceList, supportedList []uint16
771 if c.config.PreferServerCipherSuites {
772 preferenceList = c.config.cipherSuites()
773 supportedList = hs.clientHello.cipherSuites
774 } else {
775 preferenceList = hs.clientHello.cipherSuites
776 supportedList = c.config.cipherSuites()
777 }
778
779 for _, id := range preferenceList {
Nick Harper728eed82016-07-07 17:36:52 -0700780 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk, true); hs.suite != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700781 break
782 }
783 }
784
785 if hs.suite == nil {
786 c.sendAlert(alertHandshakeFailure)
787 return false, errors.New("tls: no cipher suite supported by both client and server")
788 }
789
790 return false, nil
791}
792
David Benjamin7d79f832016-07-04 09:20:45 -0700793// processClientExtensions processes all ClientHello extensions not directly
794// related to cipher suite negotiation and writes responses in serverExtensions.
795func (hs *serverHandshakeState) processClientExtensions(serverExtensions *serverExtensions) error {
796 config := hs.c.config
797 c := hs.c
798
David Benjamin8d315d72016-07-18 01:03:18 +0200799 if c.vers < VersionTLS13 || config.Bugs.NegotiateRenegotiationInfoAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700800 if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) {
801 c.sendAlert(alertHandshakeFailure)
802 return errors.New("tls: renegotiation mismatch")
David Benjamin7d79f832016-07-04 09:20:45 -0700803 }
David Benjamin7d79f832016-07-04 09:20:45 -0700804
Nick Harper728eed82016-07-07 17:36:52 -0700805 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
806 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.clientVerify...)
807 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.serverVerify...)
808 if c.config.Bugs.BadRenegotiationInfo {
809 serverExtensions.secureRenegotiation[0] ^= 0x80
810 }
811 } else {
812 serverExtensions.secureRenegotiation = hs.clientHello.secureRenegotiation
813 }
814
815 if c.noRenegotiationInfo() {
816 serverExtensions.secureRenegotiation = nil
817 }
David Benjamin7d79f832016-07-04 09:20:45 -0700818 }
819
820 serverExtensions.duplicateExtension = c.config.Bugs.DuplicateExtension
821
822 if len(hs.clientHello.serverName) > 0 {
823 c.serverName = hs.clientHello.serverName
824 }
825 if len(config.Certificates) == 0 {
826 c.sendAlert(alertInternalError)
827 return errors.New("tls: no certificates configured")
828 }
829 hs.cert = &config.Certificates[0]
830 if len(hs.clientHello.serverName) > 0 {
831 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
832 }
833 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
834 return errors.New("tls: unexpected server name")
835 }
836
837 if len(hs.clientHello.alpnProtocols) > 0 {
838 if proto := c.config.Bugs.ALPNProtocol; proto != nil {
839 serverExtensions.alpnProtocol = *proto
840 serverExtensions.alpnProtocolEmpty = len(*proto) == 0
841 c.clientProtocol = *proto
842 c.usedALPN = true
843 } else if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
844 serverExtensions.alpnProtocol = selectedProto
845 c.clientProtocol = selectedProto
846 c.usedALPN = true
847 }
848 }
Nick Harper728eed82016-07-07 17:36:52 -0700849
David Benjamin8d315d72016-07-18 01:03:18 +0200850 if c.vers < VersionTLS13 || config.Bugs.NegotiateNPNAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700851 if len(hs.clientHello.alpnProtocols) == 0 || c.config.Bugs.NegotiateALPNAndNPN {
852 // Although sending an empty NPN extension is reasonable, Firefox has
853 // had a bug around this. Best to send nothing at all if
854 // config.NextProtos is empty. See
855 // https://code.google.com/p/go/issues/detail?id=5445.
856 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
857 serverExtensions.nextProtoNeg = true
858 serverExtensions.nextProtos = config.NextProtos
859 serverExtensions.npnLast = config.Bugs.SwapNPNAndALPN
860 }
David Benjamin7d79f832016-07-04 09:20:45 -0700861 }
Steven Valdez143e8b32016-07-11 13:19:03 -0400862 }
David Benjamin7d79f832016-07-04 09:20:45 -0700863
David Benjamin8d315d72016-07-18 01:03:18 +0200864 if c.vers < VersionTLS13 || config.Bugs.NegotiateEMSAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700865 serverExtensions.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !c.config.Bugs.NoExtendedMasterSecret
Steven Valdez143e8b32016-07-11 13:19:03 -0400866 }
David Benjamin7d79f832016-07-04 09:20:45 -0700867
David Benjamin8d315d72016-07-18 01:03:18 +0200868 if c.vers < VersionTLS13 || config.Bugs.NegotiateChannelIDAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700869 if hs.clientHello.channelIDSupported && config.RequestChannelID {
870 serverExtensions.channelIDRequested = true
871 }
David Benjamin7d79f832016-07-04 09:20:45 -0700872 }
873
874 if hs.clientHello.srtpProtectionProfiles != nil {
875 SRTPLoop:
876 for _, p1 := range c.config.SRTPProtectionProfiles {
877 for _, p2 := range hs.clientHello.srtpProtectionProfiles {
878 if p1 == p2 {
879 serverExtensions.srtpProtectionProfile = p1
880 c.srtpProtectionProfile = p1
881 break SRTPLoop
882 }
883 }
884 }
885 }
886
887 if c.config.Bugs.SendSRTPProtectionProfile != 0 {
888 serverExtensions.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
889 }
890
891 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
892 if hs.clientHello.customExtension != *expected {
893 return fmt.Errorf("tls: bad custom extension contents %q", hs.clientHello.customExtension)
894 }
895 }
896 serverExtensions.customExtension = config.Bugs.CustomExtension
897
Steven Valdez143e8b32016-07-11 13:19:03 -0400898 if c.config.Bugs.AdvertiseTicketExtension {
899 serverExtensions.ticketSupported = true
900 }
901
David Benjamin7d79f832016-07-04 09:20:45 -0700902 return nil
903}
904
Adam Langley95c29f32014-06-20 12:00:00 -0700905// checkForResumption returns true if we should perform resumption on this connection.
906func (hs *serverHandshakeState) checkForResumption() bool {
907 c := hs.c
908
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500909 if len(hs.clientHello.sessionTicket) > 0 {
910 if c.config.SessionTicketsDisabled {
911 return false
912 }
David Benjaminb0c8db72014-09-24 15:19:56 -0400913
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500914 var ok bool
915 if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
916 return false
917 }
918 } else {
919 if c.config.ServerSessionCache == nil {
920 return false
921 }
922
923 var ok bool
924 sessionId := string(hs.clientHello.sessionId)
925 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
926 return false
927 }
Adam Langley95c29f32014-06-20 12:00:00 -0700928 }
929
David Benjamine18d8212014-11-10 02:37:15 -0500930 // Never resume a session for a different SSL version.
931 if !c.config.Bugs.AllowSessionVersionMismatch && c.vers != hs.sessionState.vers {
932 return false
Adam Langley95c29f32014-06-20 12:00:00 -0700933 }
934
935 cipherSuiteOk := false
936 // Check that the client is still offering the ciphersuite in the session.
937 for _, id := range hs.clientHello.cipherSuites {
938 if id == hs.sessionState.cipherSuite {
939 cipherSuiteOk = true
940 break
941 }
942 }
943 if !cipherSuiteOk {
944 return false
945 }
946
947 // Check that we also support the ciphersuite from the session.
Nick Harper728eed82016-07-07 17:36:52 -0700948 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk, true)
Adam Langley95c29f32014-06-20 12:00:00 -0700949 if hs.suite == nil {
950 return false
951 }
952
953 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
954 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
955 if needClientCerts && !sessionHasClientCerts {
956 return false
957 }
958 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
959 return false
960 }
961
962 return true
963}
964
965func (hs *serverHandshakeState) doResumeHandshake() error {
966 c := hs.c
967
968 hs.hello.cipherSuite = hs.suite.id
David Benjaminece3de92015-03-16 18:02:20 -0400969 if c.config.Bugs.SendCipherSuite != 0 {
970 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
971 }
Adam Langley95c29f32014-06-20 12:00:00 -0700972 // We echo the client's session ID in the ServerHello to let it know
973 // that we're doing a resumption.
974 hs.hello.sessionId = hs.clientHello.sessionId
Nick Harperb3d51be2016-07-01 11:43:18 -0400975 hs.hello.extensions.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -0700976
David Benjamin80d1b352016-05-04 19:19:06 -0400977 if c.config.Bugs.SendSCTListOnResume != nil {
Nick Harperb3d51be2016-07-01 11:43:18 -0400978 hs.hello.extensions.sctList = c.config.Bugs.SendSCTListOnResume
David Benjamin80d1b352016-05-04 19:19:06 -0400979 }
980
Adam Langley95c29f32014-06-20 12:00:00 -0700981 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -0400982 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -0400983 hs.writeClientHash(hs.clientHello.marshal())
984 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700985
986 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
987
988 if len(hs.sessionState.certificates) > 0 {
989 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
990 return err
991 }
992 }
993
994 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -0700995 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700996
997 return nil
998}
999
1000func (hs *serverHandshakeState) doFullHandshake() error {
1001 config := hs.c.config
1002 c := hs.c
1003
David Benjamin48cae082014-10-27 01:06:24 -04001004 isPSK := hs.suite.flags&suitePSK != 0
1005 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001006 hs.hello.extensions.ocspStapling = true
Adam Langley95c29f32014-06-20 12:00:00 -07001007 }
1008
David Benjamin61f95272014-11-25 01:55:35 -05001009 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001010 hs.hello.extensions.sctList = hs.cert.SignedCertificateTimestampList
David Benjamin61f95272014-11-25 01:55:35 -05001011 }
1012
Nick Harperb3d51be2016-07-01 11:43:18 -04001013 hs.hello.extensions.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
Adam Langley95c29f32014-06-20 12:00:00 -07001014 hs.hello.cipherSuite = hs.suite.id
David Benjamin6095de82014-12-27 01:50:38 -05001015 if config.Bugs.SendCipherSuite != 0 {
1016 hs.hello.cipherSuite = config.Bugs.SendCipherSuite
1017 }
Nick Harperb3d51be2016-07-01 11:43:18 -04001018 c.extendedMasterSecret = hs.hello.extensions.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -07001019
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001020 // Generate a session ID if we're to save the session.
Nick Harperb3d51be2016-07-01 11:43:18 -04001021 if !hs.hello.extensions.ticketSupported && config.ServerSessionCache != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001022 hs.hello.sessionId = make([]byte, 32)
1023 if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
1024 c.sendAlert(alertInternalError)
1025 return errors.New("tls: short read from Rand: " + err.Error())
1026 }
1027 }
1028
Adam Langley95c29f32014-06-20 12:00:00 -07001029 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -04001030 hs.writeClientHash(hs.clientHello.marshal())
1031 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001032
1033 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
1034
David Benjamin48cae082014-10-27 01:06:24 -04001035 if !isPSK {
1036 certMsg := new(certificateMsg)
David Benjamin8923c0b2015-06-07 11:42:34 -04001037 if !config.Bugs.EmptyCertificateList {
1038 certMsg.certificates = hs.cert.Certificate
1039 }
David Benjamin48cae082014-10-27 01:06:24 -04001040 if !config.Bugs.UnauthenticatedECDH {
David Benjaminbcb2d912015-02-24 23:45:43 -05001041 certMsgBytes := certMsg.marshal()
David Benjaminbcb2d912015-02-24 23:45:43 -05001042 hs.writeServerHash(certMsgBytes)
1043 c.writeRecord(recordTypeHandshake, certMsgBytes)
David Benjamin48cae082014-10-27 01:06:24 -04001044 }
David Benjamin1c375dd2014-07-12 00:48:23 -04001045 }
Adam Langley95c29f32014-06-20 12:00:00 -07001046
Nick Harperb3d51be2016-07-01 11:43:18 -04001047 if hs.hello.extensions.ocspStapling && !c.config.Bugs.SkipCertificateStatus {
Adam Langley95c29f32014-06-20 12:00:00 -07001048 certStatus := new(certificateStatusMsg)
1049 certStatus.statusType = statusTypeOCSP
1050 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -04001051 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001052 c.writeRecord(recordTypeHandshake, certStatus.marshal())
1053 }
1054
1055 keyAgreement := hs.suite.ka(c.vers)
1056 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
1057 if err != nil {
1058 c.sendAlert(alertHandshakeFailure)
1059 return err
1060 }
Steven Valdez5440fe02016-07-18 12:40:30 -04001061 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
1062 c.curveID = ecdhe.curveID
1063 }
David Benjamin9c651c92014-07-12 13:27:45 -04001064 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -04001065 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001066 c.writeRecord(recordTypeHandshake, skx.marshal())
1067 }
1068
1069 if config.ClientAuth >= RequestClientCert {
1070 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -04001071 certReq := &certificateRequestMsg{
1072 certificateTypes: config.ClientCertificateTypes,
1073 }
1074 if certReq.certificateTypes == nil {
1075 certReq.certificateTypes = []byte{
1076 byte(CertTypeRSASign),
1077 byte(CertTypeECDSASign),
1078 }
Adam Langley95c29f32014-06-20 12:00:00 -07001079 }
1080 if c.vers >= VersionTLS12 {
Nick Harper60edffd2016-06-21 15:19:24 -07001081 certReq.hasSignatureAlgorithm = true
1082 if !config.Bugs.NoSignatureAlgorithms {
David Benjamin7a41d372016-07-09 11:21:54 -07001083 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin000800a2014-11-14 01:43:59 -05001084 }
Adam Langley95c29f32014-06-20 12:00:00 -07001085 }
1086
1087 // An empty list of certificateAuthorities signals to
1088 // the client that it may send any certificate in response
1089 // to our request. When we know the CAs we trust, then
1090 // we can send them down, so that the client can choose
1091 // an appropriate certificate to give to us.
1092 if config.ClientCAs != nil {
1093 certReq.certificateAuthorities = config.ClientCAs.Subjects()
1094 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001095 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001096 c.writeRecord(recordTypeHandshake, certReq.marshal())
1097 }
1098
1099 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001100 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001101 c.writeRecord(recordTypeHandshake, helloDone.marshal())
David Benjamin582ba042016-07-07 12:33:25 -07001102 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001103
1104 var pub crypto.PublicKey // public key for client auth, if any
1105
David Benjamin83f90402015-01-27 01:09:43 -05001106 if err := c.simulatePacketLoss(nil); err != nil {
1107 return err
1108 }
Adam Langley95c29f32014-06-20 12:00:00 -07001109 msg, err := c.readHandshake()
1110 if err != nil {
1111 return err
1112 }
1113
1114 var ok bool
1115 // If we requested a client certificate, then the client must send a
1116 // certificate message, even if it's empty.
1117 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -04001118 var certMsg *certificateMsg
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001119 var certificates [][]byte
1120 if certMsg, ok = msg.(*certificateMsg); ok {
1121 if c.vers == VersionSSL30 && len(certMsg.certificates) == 0 {
1122 return errors.New("tls: empty certificate message in SSL 3.0")
1123 }
1124
1125 hs.writeClientHash(certMsg.marshal())
1126 certificates = certMsg.certificates
1127 } else if c.vers != VersionSSL30 {
1128 // In TLS, the Certificate message is required. In SSL
1129 // 3.0, the peer skips it when sending no certificates.
Adam Langley95c29f32014-06-20 12:00:00 -07001130 c.sendAlert(alertUnexpectedMessage)
1131 return unexpectedMessageError(certMsg, msg)
1132 }
Adam Langley95c29f32014-06-20 12:00:00 -07001133
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001134 if len(certificates) == 0 {
Adam Langley95c29f32014-06-20 12:00:00 -07001135 // The client didn't actually send a certificate
1136 switch config.ClientAuth {
1137 case RequireAnyClientCert, RequireAndVerifyClientCert:
1138 c.sendAlert(alertBadCertificate)
1139 return errors.New("tls: client didn't provide a certificate")
1140 }
1141 }
1142
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001143 pub, err = hs.processCertsFromClient(certificates)
Adam Langley95c29f32014-06-20 12:00:00 -07001144 if err != nil {
1145 return err
1146 }
1147
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001148 if ok {
1149 msg, err = c.readHandshake()
1150 if err != nil {
1151 return err
1152 }
Adam Langley95c29f32014-06-20 12:00:00 -07001153 }
1154 }
1155
1156 // Get client key exchange
1157 ckx, ok := msg.(*clientKeyExchangeMsg)
1158 if !ok {
1159 c.sendAlert(alertUnexpectedMessage)
1160 return unexpectedMessageError(ckx, msg)
1161 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001162 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001163
David Benjamine098ec22014-08-27 23:13:20 -04001164 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
1165 if err != nil {
1166 c.sendAlert(alertHandshakeFailure)
1167 return err
1168 }
Adam Langley75712922014-10-10 16:23:43 -07001169 if c.extendedMasterSecret {
1170 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1171 } else {
1172 if c.config.Bugs.RequireExtendedMasterSecret {
1173 return errors.New("tls: extended master secret required but not supported by peer")
1174 }
1175 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
1176 }
David Benjamine098ec22014-08-27 23:13:20 -04001177
Adam Langley95c29f32014-06-20 12:00:00 -07001178 // If we received a client cert in response to our certificate request message,
1179 // the client will send us a certificateVerifyMsg immediately after the
1180 // clientKeyExchangeMsg. This message is a digest of all preceding
1181 // handshake-layer messages that is signed using the private key corresponding
1182 // to the client's certificate. This allows us to verify that the client is in
1183 // possession of the private key of the certificate.
1184 if len(c.peerCertificates) > 0 {
1185 msg, err = c.readHandshake()
1186 if err != nil {
1187 return err
1188 }
1189 certVerify, ok := msg.(*certificateVerifyMsg)
1190 if !ok {
1191 c.sendAlert(alertUnexpectedMessage)
1192 return unexpectedMessageError(certVerify, msg)
1193 }
1194
David Benjaminde620d92014-07-18 15:03:41 -04001195 // Determine the signature type.
Nick Harper60edffd2016-06-21 15:19:24 -07001196 var sigAlg signatureAlgorithm
1197 if certVerify.hasSignatureAlgorithm {
1198 sigAlg = certVerify.signatureAlgorithm
Nick Harper60edffd2016-06-21 15:19:24 -07001199 c.peerSignatureAlgorithm = sigAlg
David Benjaminde620d92014-07-18 15:03:41 -04001200 }
1201
Nick Harper60edffd2016-06-21 15:19:24 -07001202 if c.vers > VersionSSL30 {
David Benjamin1fb125c2016-07-08 18:52:12 -07001203 err = verifyMessage(c.vers, pub, c.config, sigAlg, hs.finishedHash.buffer, certVerify.signature)
Nick Harper60edffd2016-06-21 15:19:24 -07001204 } else {
1205 // SSL 3.0's client certificate construction is
1206 // incompatible with signatureAlgorithm.
1207 rsaPub, ok := pub.(*rsa.PublicKey)
1208 if !ok {
1209 err = errors.New("unsupported key type for client certificate")
1210 } else {
1211 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
1212 err = rsa.VerifyPKCS1v15(rsaPub, crypto.MD5SHA1, digest, certVerify.signature)
David Benjaminde620d92014-07-18 15:03:41 -04001213 }
Adam Langley95c29f32014-06-20 12:00:00 -07001214 }
1215 if err != nil {
1216 c.sendAlert(alertBadCertificate)
1217 return errors.New("could not validate signature of connection nonces: " + err.Error())
1218 }
1219
David Benjamin83c0bc92014-08-04 01:23:53 -04001220 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001221 }
1222
David Benjamine098ec22014-08-27 23:13:20 -04001223 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001224
1225 return nil
1226}
1227
1228func (hs *serverHandshakeState) establishKeys() error {
1229 c := hs.c
1230
1231 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001232 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 -07001233
1234 var clientCipher, serverCipher interface{}
1235 var clientHash, serverHash macFunction
1236
1237 if hs.suite.aead == nil {
1238 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
1239 clientHash = hs.suite.mac(c.vers, clientMAC)
1240 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
1241 serverHash = hs.suite.mac(c.vers, serverMAC)
1242 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001243 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1244 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001245 }
1246
1247 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
1248 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
1249
1250 return nil
1251}
1252
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001253func (hs *serverHandshakeState) readFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001254 c := hs.c
1255
1256 c.readRecord(recordTypeChangeCipherSpec)
1257 if err := c.in.error(); err != nil {
1258 return err
1259 }
1260
Nick Harperb3d51be2016-07-01 11:43:18 -04001261 if hs.hello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001262 msg, err := c.readHandshake()
1263 if err != nil {
1264 return err
1265 }
1266 nextProto, ok := msg.(*nextProtoMsg)
1267 if !ok {
1268 c.sendAlert(alertUnexpectedMessage)
1269 return unexpectedMessageError(nextProto, msg)
1270 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001271 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001272 c.clientProtocol = nextProto.proto
1273 }
1274
Nick Harperb3d51be2016-07-01 11:43:18 -04001275 if hs.hello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001276 msg, err := c.readHandshake()
1277 if err != nil {
1278 return err
1279 }
David Benjamin24599a82016-06-30 18:56:53 -04001280 channelIDMsg, ok := msg.(*channelIDMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001281 if !ok {
1282 c.sendAlert(alertUnexpectedMessage)
David Benjamin24599a82016-06-30 18:56:53 -04001283 return unexpectedMessageError(channelIDMsg, msg)
David Benjamind30a9902014-08-24 01:44:23 -04001284 }
David Benjamin24599a82016-06-30 18:56:53 -04001285 x := new(big.Int).SetBytes(channelIDMsg.channelID[0:32])
1286 y := new(big.Int).SetBytes(channelIDMsg.channelID[32:64])
1287 r := new(big.Int).SetBytes(channelIDMsg.channelID[64:96])
1288 s := new(big.Int).SetBytes(channelIDMsg.channelID[96:128])
David Benjamind30a9902014-08-24 01:44:23 -04001289 if !elliptic.P256().IsOnCurve(x, y) {
1290 return errors.New("tls: invalid channel ID public key")
1291 }
1292 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
1293 var resumeHash []byte
1294 if isResume {
1295 resumeHash = hs.sessionState.handshakeHash
1296 }
1297 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
1298 return errors.New("tls: invalid channel ID signature")
1299 }
1300 c.channelID = channelID
1301
David Benjamin24599a82016-06-30 18:56:53 -04001302 hs.writeClientHash(channelIDMsg.marshal())
David Benjamind30a9902014-08-24 01:44:23 -04001303 }
1304
Adam Langley95c29f32014-06-20 12:00:00 -07001305 msg, err := c.readHandshake()
1306 if err != nil {
1307 return err
1308 }
1309 clientFinished, ok := msg.(*finishedMsg)
1310 if !ok {
1311 c.sendAlert(alertUnexpectedMessage)
1312 return unexpectedMessageError(clientFinished, msg)
1313 }
1314
1315 verify := hs.finishedHash.clientSum(hs.masterSecret)
1316 if len(verify) != len(clientFinished.verifyData) ||
1317 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
1318 c.sendAlert(alertHandshakeFailure)
1319 return errors.New("tls: client's Finished message is incorrect")
1320 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001321 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001322 copy(out, clientFinished.verifyData)
Adam Langley95c29f32014-06-20 12:00:00 -07001323
David Benjamin83c0bc92014-08-04 01:23:53 -04001324 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001325 return nil
1326}
1327
1328func (hs *serverHandshakeState) sendSessionTicket() error {
Adam Langley95c29f32014-06-20 12:00:00 -07001329 c := hs.c
Adam Langley95c29f32014-06-20 12:00:00 -07001330 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -04001331 vers: c.vers,
1332 cipherSuite: hs.suite.id,
1333 masterSecret: hs.masterSecret,
1334 certificates: hs.certsFromClient,
1335 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -07001336 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001337
Nick Harperb3d51be2016-07-01 11:43:18 -04001338 if !hs.hello.extensions.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001339 if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
1340 c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
1341 }
1342 return nil
1343 }
1344
1345 m := new(newSessionTicketMsg)
1346
David Benjamindd6fed92015-10-23 17:41:12 -04001347 if !c.config.Bugs.SendEmptySessionTicket {
1348 var err error
1349 m.ticket, err = c.encryptTicket(&state)
1350 if err != nil {
1351 return err
1352 }
Adam Langley95c29f32014-06-20 12:00:00 -07001353 }
Adam Langley95c29f32014-06-20 12:00:00 -07001354
David Benjamin83c0bc92014-08-04 01:23:53 -04001355 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001356 c.writeRecord(recordTypeHandshake, m.marshal())
1357
1358 return nil
1359}
1360
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001361func (hs *serverHandshakeState) sendFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001362 c := hs.c
1363
David Benjamin86271ee2014-07-21 16:14:03 -04001364 finished := new(finishedMsg)
1365 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001366 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001367 if c.config.Bugs.BadFinished {
1368 finished.verifyData[0]++
1369 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001370 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001371 hs.finishedBytes = finished.marshal()
1372 hs.writeServerHash(hs.finishedBytes)
1373 postCCSBytes := hs.finishedBytes
David Benjamin86271ee2014-07-21 16:14:03 -04001374
1375 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
1376 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
1377 postCCSBytes = postCCSBytes[5:]
David Benjamin61672812016-07-14 23:10:43 -04001378 } else if c.config.Bugs.SendUnencryptedFinished {
1379 c.writeRecord(recordTypeHandshake, postCCSBytes)
1380 postCCSBytes = nil
David Benjamin86271ee2014-07-21 16:14:03 -04001381 }
David Benjamin582ba042016-07-07 12:33:25 -07001382 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001383
David Benjamina0e52232014-07-19 17:39:58 -04001384 if !c.config.Bugs.SkipChangeCipherSpec {
David Benjamin8411b242015-11-26 12:07:28 -05001385 ccs := []byte{1}
1386 if c.config.Bugs.BadChangeCipherSpec != nil {
1387 ccs = c.config.Bugs.BadChangeCipherSpec
1388 }
1389 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamina0e52232014-07-19 17:39:58 -04001390 }
Adam Langley95c29f32014-06-20 12:00:00 -07001391
David Benjamin4189bd92015-01-25 23:52:39 -05001392 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1393 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1394 }
David Benjamindc3da932015-03-12 15:09:02 -04001395 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1396 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1397 return errors.New("tls: simulating post-CCS alert")
1398 }
David Benjamin4189bd92015-01-25 23:52:39 -05001399
David Benjamin61672812016-07-14 23:10:43 -04001400 if !c.config.Bugs.SkipFinished && len(postCCSBytes) > 0 {
David Benjaminb80168e2015-02-08 18:30:14 -05001401 c.writeRecord(recordTypeHandshake, postCCSBytes)
David Benjamin12d2c482016-07-24 10:56:51 -04001402 if !c.config.Bugs.PackHelloRequestWithFinished {
1403 // Defer flushing until renegotiation.
1404 c.flushHandshake()
1405 }
David Benjaminb3774b92015-01-31 17:16:01 -05001406 }
Adam Langley95c29f32014-06-20 12:00:00 -07001407
David Benjaminc565ebb2015-04-03 04:06:36 -04001408 c.cipherSuite = hs.suite
Adam Langley95c29f32014-06-20 12:00:00 -07001409
1410 return nil
1411}
1412
1413// processCertsFromClient takes a chain of client certificates either from a
1414// Certificates message or from a sessionState and verifies them. It returns
1415// the public key of the leaf certificate.
1416func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
1417 c := hs.c
1418
1419 hs.certsFromClient = certificates
1420 certs := make([]*x509.Certificate, len(certificates))
1421 var err error
1422 for i, asn1Data := range certificates {
1423 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
1424 c.sendAlert(alertBadCertificate)
1425 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
1426 }
1427 }
1428
1429 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
1430 opts := x509.VerifyOptions{
1431 Roots: c.config.ClientCAs,
1432 CurrentTime: c.config.time(),
1433 Intermediates: x509.NewCertPool(),
1434 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
1435 }
1436
1437 for _, cert := range certs[1:] {
1438 opts.Intermediates.AddCert(cert)
1439 }
1440
1441 chains, err := certs[0].Verify(opts)
1442 if err != nil {
1443 c.sendAlert(alertBadCertificate)
1444 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
1445 }
1446
1447 ok := false
1448 for _, ku := range certs[0].ExtKeyUsage {
1449 if ku == x509.ExtKeyUsageClientAuth {
1450 ok = true
1451 break
1452 }
1453 }
1454 if !ok {
1455 c.sendAlert(alertHandshakeFailure)
1456 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
1457 }
1458
1459 c.verifiedChains = chains
1460 }
1461
1462 if len(certs) > 0 {
1463 var pub crypto.PublicKey
1464 switch key := certs[0].PublicKey.(type) {
1465 case *ecdsa.PublicKey, *rsa.PublicKey:
1466 pub = key
1467 default:
1468 c.sendAlert(alertUnsupportedCertificate)
1469 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
1470 }
1471 c.peerCertificates = certs
1472 return pub, nil
1473 }
1474
1475 return nil, nil
1476}
1477
David Benjamin83c0bc92014-08-04 01:23:53 -04001478func (hs *serverHandshakeState) writeServerHash(msg []byte) {
1479 // writeServerHash is called before writeRecord.
1480 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1481}
1482
1483func (hs *serverHandshakeState) writeClientHash(msg []byte) {
1484 // writeClientHash is called after readHandshake.
1485 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1486}
1487
1488func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
1489 if hs.c.isDTLS {
1490 // This is somewhat hacky. DTLS hashes a slightly different format.
1491 // First, the TLS header.
1492 hs.finishedHash.Write(msg[:4])
1493 // Then the sequence number and reassembled fragment offset (always 0).
1494 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1495 // Then the reassembled fragment (always equal to the message length).
1496 hs.finishedHash.Write(msg[1:4])
1497 // And then the message body.
1498 hs.finishedHash.Write(msg[4:])
1499 } else {
1500 hs.finishedHash.Write(msg)
1501 }
1502}
1503
Adam Langley95c29f32014-06-20 12:00:00 -07001504// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
1505// is acceptable to use.
Nick Harper728eed82016-07-07 17:36:52 -07001506func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk, pskOk bool) *cipherSuite {
Adam Langley95c29f32014-06-20 12:00:00 -07001507 for _, supported := range supportedCipherSuites {
1508 if id == supported {
1509 var candidate *cipherSuite
1510
1511 for _, s := range cipherSuites {
1512 if s.id == id {
1513 candidate = s
1514 break
1515 }
1516 }
1517 if candidate == nil {
1518 continue
1519 }
1520 // Don't select a ciphersuite which we can't
1521 // support for this client.
David Benjamin0407e762016-06-17 16:41:18 -04001522 if !c.config.Bugs.EnableAllCiphers {
Nick Harper728eed82016-07-07 17:36:52 -07001523 if (candidate.flags&suitePSK != 0) && !pskOk {
1524 continue
1525 }
David Benjamin0407e762016-06-17 16:41:18 -04001526 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
1527 continue
1528 }
1529 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
1530 continue
1531 }
1532 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
1533 continue
1534 }
Nick Harper728eed82016-07-07 17:36:52 -07001535 if version >= VersionTLS13 && candidate.flags&suiteTLS13 == 0 {
1536 continue
1537 }
David Benjamin0407e762016-06-17 16:41:18 -04001538 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
1539 continue
1540 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001541 }
Adam Langley95c29f32014-06-20 12:00:00 -07001542 return candidate
1543 }
1544 }
1545
1546 return nil
1547}
David Benjaminf93995b2015-11-05 18:23:20 -05001548
1549func isTLS12Cipher(id uint16) bool {
1550 for _, cipher := range cipherSuites {
1551 if cipher.id != id {
1552 continue
1553 }
1554 return cipher.flags&suiteTLS12 != 0
1555 }
1556 // Unknown cipher.
1557 return false
1558}