blob: 4d8b5c161afbcdb493fc3be24a766e6a7a3be842 [file] [log] [blame]
Adam Langley95c29f32014-06-20 12:00:00 -07001// Copyright 2009 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
Adam Langleydc7e9c42015-09-29 15:21:04 -07005package runner
Adam Langley95c29f32014-06-20 12:00:00 -07006
7import (
David Benjamin83c0bc92014-08-04 01:23:53 -04008 "bytes"
Adam Langley95c29f32014-06-20 12:00:00 -07009 "crypto"
10 "crypto/ecdsa"
David Benjamind30a9902014-08-24 01:44:23 -040011 "crypto/elliptic"
Adam Langley95c29f32014-06-20 12:00:00 -070012 "crypto/rsa"
13 "crypto/subtle"
14 "crypto/x509"
Adam Langley95c29f32014-06-20 12:00:00 -070015 "errors"
16 "fmt"
17 "io"
David Benjamind30a9902014-08-24 01:44:23 -040018 "math/big"
Adam Langley95c29f32014-06-20 12:00:00 -070019)
20
21// serverHandshakeState contains details of a server handshake in progress.
22// It's discarded once the handshake has completed.
23type serverHandshakeState struct {
24 c *Conn
25 clientHello *clientHelloMsg
26 hello *serverHelloMsg
27 suite *cipherSuite
28 ellipticOk bool
29 ecdsaOk bool
30 sessionState *sessionState
31 finishedHash finishedHash
32 masterSecret []byte
33 certsFromClient [][]byte
34 cert *Certificate
David Benjamin83f90402015-01-27 01:09:43 -050035 finishedBytes []byte
Adam Langley95c29f32014-06-20 12:00:00 -070036}
37
38// serverHandshake performs a TLS handshake as a server.
39func (c *Conn) serverHandshake() error {
40 config := c.config
41
42 // If this is the first server handshake, we generate a random key to
43 // encrypt the tickets with.
44 config.serverInitOnce.Do(config.serverInit)
45
David Benjamin83c0bc92014-08-04 01:23:53 -040046 c.sendHandshakeSeq = 0
47 c.recvHandshakeSeq = 0
48
Adam Langley95c29f32014-06-20 12:00:00 -070049 hs := serverHandshakeState{
50 c: c,
51 }
David Benjaminf25dda92016-07-04 10:05:26 -070052 if err := hs.readClientHello(); err != nil {
53 return err
54 }
Adam Langley95c29f32014-06-20 12:00:00 -070055
David Benjamin8d315d72016-07-18 01:03:18 +020056 if c.vers >= VersionTLS13 {
Nick Harper728eed82016-07-07 17:36:52 -070057 if err := hs.doTLS13Handshake(); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -070058 return err
59 }
Nick Harper728eed82016-07-07 17:36:52 -070060 } else {
61 isResume, err := hs.processClientHello()
62 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -070063 return err
64 }
Nick Harper728eed82016-07-07 17:36:52 -070065
66 // For an overview of TLS handshaking, see https://tools.ietf.org/html/rfc5246#section-7.3
67 if isResume {
68 // The client has included a session ticket and so we do an abbreviated handshake.
69 if err := hs.doResumeHandshake(); err != nil {
70 return err
71 }
72 if err := hs.establishKeys(); err != nil {
73 return err
74 }
75 if c.config.Bugs.RenewTicketOnResume {
76 if err := hs.sendSessionTicket(); err != nil {
77 return err
78 }
79 }
80 if err := hs.sendFinished(c.firstFinished[:]); err != nil {
81 return err
82 }
83 // Most retransmits are triggered by a timeout, but the final
84 // leg of the handshake is retransmited upon re-receiving a
85 // Finished.
86 if err := c.simulatePacketLoss(func() {
David Benjamin02edcd02016-07-27 17:40:37 -040087 c.sendHandshakeSeq--
Nick Harper728eed82016-07-07 17:36:52 -070088 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
89 c.flushHandshake()
90 }); err != nil {
91 return err
92 }
93 if err := hs.readFinished(nil, isResume); err != nil {
94 return err
95 }
96 c.didResume = true
97 } else {
98 // The client didn't include a session ticket, or it wasn't
99 // valid so we do a full handshake.
100 if err := hs.doFullHandshake(); err != nil {
101 return err
102 }
103 if err := hs.establishKeys(); err != nil {
104 return err
105 }
106 if err := hs.readFinished(c.firstFinished[:], isResume); err != nil {
107 return err
108 }
109 if c.config.Bugs.AlertBeforeFalseStartTest != 0 {
110 c.sendAlert(c.config.Bugs.AlertBeforeFalseStartTest)
111 }
112 if c.config.Bugs.ExpectFalseStart {
113 if err := c.readRecord(recordTypeApplicationData); err != nil {
114 return fmt.Errorf("tls: peer did not false start: %s", err)
115 }
116 }
David Benjaminbed9aae2014-08-07 19:13:38 -0400117 if err := hs.sendSessionTicket(); err != nil {
118 return err
119 }
Nick Harper728eed82016-07-07 17:36:52 -0700120 if err := hs.sendFinished(nil); err != nil {
121 return err
David Benjamine58c4f52014-08-24 03:47:07 -0400122 }
123 }
David Benjamin97a0a082016-07-13 17:57:35 -0400124
125 c.exporterSecret = hs.masterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700126 }
127 c.handshakeComplete = true
David Benjaminc565ebb2015-04-03 04:06:36 -0400128 copy(c.clientRandom[:], hs.clientHello.random)
129 copy(c.serverRandom[:], hs.hello.random)
Adam Langley95c29f32014-06-20 12:00:00 -0700130
131 return nil
132}
133
David Benjaminf25dda92016-07-04 10:05:26 -0700134// readClientHello reads a ClientHello message from the client and determines
135// the protocol version.
136func (hs *serverHandshakeState) readClientHello() error {
Adam Langley95c29f32014-06-20 12:00:00 -0700137 config := hs.c.config
138 c := hs.c
139
David Benjamin83f90402015-01-27 01:09:43 -0500140 if err := c.simulatePacketLoss(nil); err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700141 return err
David Benjamin83f90402015-01-27 01:09:43 -0500142 }
Adam Langley95c29f32014-06-20 12:00:00 -0700143 msg, err := c.readHandshake()
144 if err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700145 return err
Adam Langley95c29f32014-06-20 12:00:00 -0700146 }
147 var ok bool
148 hs.clientHello, ok = msg.(*clientHelloMsg)
149 if !ok {
150 c.sendAlert(alertUnexpectedMessage)
David Benjaminf25dda92016-07-04 10:05:26 -0700151 return unexpectedMessageError(hs.clientHello, msg)
Adam Langley95c29f32014-06-20 12:00:00 -0700152 }
Adam Langley33ad2b52015-07-20 17:43:53 -0700153 if size := config.Bugs.RequireClientHelloSize; size != 0 && len(hs.clientHello.raw) != size {
David Benjaminf25dda92016-07-04 10:05:26 -0700154 return fmt.Errorf("tls: ClientHello record size is %d, but expected %d", len(hs.clientHello.raw), size)
Feng Lu41aa3252014-11-21 22:47:56 -0800155 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400156
157 if c.isDTLS && !config.Bugs.SkipHelloVerifyRequest {
David Benjamin8bc38f52014-08-16 12:07:27 -0400158 // Per RFC 6347, the version field in HelloVerifyRequest SHOULD
159 // be always DTLS 1.0
David Benjamin83c0bc92014-08-04 01:23:53 -0400160 helloVerifyRequest := &helloVerifyRequestMsg{
David Benjamin8bc38f52014-08-16 12:07:27 -0400161 vers: VersionTLS10,
David Benjamin83c0bc92014-08-04 01:23:53 -0400162 cookie: make([]byte, 32),
163 }
164 if _, err := io.ReadFull(c.config.rand(), helloVerifyRequest.cookie); err != nil {
165 c.sendAlert(alertInternalError)
David Benjaminf25dda92016-07-04 10:05:26 -0700166 return errors.New("dtls: short read from Rand: " + err.Error())
David Benjamin83c0bc92014-08-04 01:23:53 -0400167 }
168 c.writeRecord(recordTypeHandshake, helloVerifyRequest.marshal())
David Benjamin582ba042016-07-07 12:33:25 -0700169 c.flushHandshake()
David Benjamin83c0bc92014-08-04 01:23:53 -0400170
David Benjamin83f90402015-01-27 01:09:43 -0500171 if err := c.simulatePacketLoss(nil); err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700172 return err
David Benjamin83f90402015-01-27 01:09:43 -0500173 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400174 msg, err := c.readHandshake()
175 if err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700176 return err
David Benjamin83c0bc92014-08-04 01:23:53 -0400177 }
178 newClientHello, ok := msg.(*clientHelloMsg)
179 if !ok {
180 c.sendAlert(alertUnexpectedMessage)
David Benjaminf25dda92016-07-04 10:05:26 -0700181 return unexpectedMessageError(hs.clientHello, msg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400182 }
183 if !bytes.Equal(newClientHello.cookie, helloVerifyRequest.cookie) {
David Benjaminf25dda92016-07-04 10:05:26 -0700184 return errors.New("dtls: invalid cookie")
David Benjamin83c0bc92014-08-04 01:23:53 -0400185 }
David Benjaminf2fedef2014-08-16 01:37:34 -0400186
187 // Apart from the cookie, the two ClientHellos must
188 // match. Note that clientHello.equal compares the
189 // serialization, so we make a copy.
190 oldClientHelloCopy := *hs.clientHello
191 oldClientHelloCopy.raw = nil
192 oldClientHelloCopy.cookie = nil
193 newClientHelloCopy := *newClientHello
194 newClientHelloCopy.raw = nil
195 newClientHelloCopy.cookie = nil
196 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
David Benjaminf25dda92016-07-04 10:05:26 -0700197 return errors.New("dtls: retransmitted ClientHello does not match")
David Benjamin83c0bc92014-08-04 01:23:53 -0400198 }
199 hs.clientHello = newClientHello
200 }
201
David Benjaminc44b1df2014-11-23 12:11:01 -0500202 if config.Bugs.RequireSameRenegoClientVersion && c.clientVersion != 0 {
203 if c.clientVersion != hs.clientHello.vers {
David Benjaminf25dda92016-07-04 10:05:26 -0700204 return fmt.Errorf("tls: client offered different version on renego")
David Benjaminc44b1df2014-11-23 12:11:01 -0500205 }
206 }
207 c.clientVersion = hs.clientHello.vers
208
David Benjamin6ae7f072015-01-26 10:22:13 -0500209 // Reject < 1.2 ClientHellos with signature_algorithms.
Nick Harper60edffd2016-06-21 15:19:24 -0700210 if c.clientVersion < VersionTLS12 && len(hs.clientHello.signatureAlgorithms) > 0 {
David Benjaminf25dda92016-07-04 10:05:26 -0700211 return fmt.Errorf("tls: client included signature_algorithms before TLS 1.2")
David Benjamin72dc7832015-03-16 17:49:43 -0400212 }
David Benjamin6ae7f072015-01-26 10:22:13 -0500213
David Benjaminf93995b2015-11-05 18:23:20 -0500214 // Check the client cipher list is consistent with the version.
215 if hs.clientHello.vers < VersionTLS12 {
216 for _, id := range hs.clientHello.cipherSuites {
217 if isTLS12Cipher(id) {
David Benjaminf25dda92016-07-04 10:05:26 -0700218 return fmt.Errorf("tls: client offered TLS 1.2 cipher before TLS 1.2")
David Benjaminf93995b2015-11-05 18:23:20 -0500219 }
220 }
221 }
222
David Benjamin1f61f0d2016-07-10 12:20:35 -0400223 if config.Bugs.NegotiateVersion != 0 {
224 c.vers = config.Bugs.NegotiateVersion
225 } else {
226 c.vers, ok = config.mutualVersion(hs.clientHello.vers, c.isDTLS)
227 if !ok {
228 c.sendAlert(alertProtocolVersion)
229 return fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
230 }
David Benjamin8bc38f52014-08-16 12:07:27 -0400231 }
Adam Langley95c29f32014-06-20 12:00:00 -0700232 c.haveVers = true
233
David Benjaminf25dda92016-07-04 10:05:26 -0700234 var scsvFound bool
235 for _, cipherSuite := range hs.clientHello.cipherSuites {
236 if cipherSuite == fallbackSCSV {
237 scsvFound = true
238 break
239 }
240 }
241
242 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
243 return errors.New("tls: no fallback SCSV found when expected")
244 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
245 return errors.New("tls: fallback SCSV found when not expected")
246 }
247
248 if config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
David Benjamin7a41d372016-07-09 11:21:54 -0700249 hs.clientHello.signatureAlgorithms = config.signSignatureAlgorithms()
David Benjaminf25dda92016-07-04 10:05:26 -0700250 }
251 if config.Bugs.IgnorePeerCurvePreferences {
252 hs.clientHello.supportedCurves = config.curvePreferences()
253 }
254 if config.Bugs.IgnorePeerCipherPreferences {
255 hs.clientHello.cipherSuites = config.cipherSuites()
256 }
257
258 return nil
259}
260
Nick Harper728eed82016-07-07 17:36:52 -0700261func (hs *serverHandshakeState) doTLS13Handshake() error {
262 c := hs.c
263 config := c.config
264
265 hs.hello = &serverHelloMsg{
266 isDTLS: c.isDTLS,
267 vers: c.vers,
268 }
269
Steven Valdez5440fe02016-07-18 12:40:30 -0400270 if config.Bugs.SendServerHelloVersion != 0 {
271 hs.hello.vers = config.Bugs.SendServerHelloVersion
272 }
273
Nick Harper728eed82016-07-07 17:36:52 -0700274 hs.hello.random = make([]byte, 32)
275 if _, err := io.ReadFull(config.rand(), hs.hello.random); err != nil {
276 c.sendAlert(alertInternalError)
277 return err
278 }
279
280 // TLS 1.3 forbids clients from advertising any non-null compression.
281 if len(hs.clientHello.compressionMethods) != 1 || hs.clientHello.compressionMethods[0] != compressionNone {
282 return errors.New("tls: client sent compression method other than null for TLS 1.3")
283 }
284
285 // Prepare an EncryptedExtensions message, but do not send it yet.
286 encryptedExtensions := new(encryptedExtensionsMsg)
Steven Valdez143e8b32016-07-11 13:19:03 -0400287 encryptedExtensions.empty = config.Bugs.EmptyEncryptedExtensions
Nick Harper728eed82016-07-07 17:36:52 -0700288 if err := hs.processClientExtensions(&encryptedExtensions.extensions); err != nil {
289 return err
290 }
291
292 supportedCurve := false
293 var selectedCurve CurveID
294 preferredCurves := config.curvePreferences()
295Curves:
296 for _, curve := range hs.clientHello.supportedCurves {
297 for _, supported := range preferredCurves {
298 if supported == curve {
299 supportedCurve = true
300 selectedCurve = curve
301 break Curves
302 }
303 }
304 }
305
306 _, ecdsaOk := hs.cert.PrivateKey.(*ecdsa.PrivateKey)
307
308 // TODO(davidben): Implement PSK support.
309 pskOk := false
310
311 // Select the cipher suite.
312 var preferenceList, supportedList []uint16
313 if config.PreferServerCipherSuites {
314 preferenceList = config.cipherSuites()
315 supportedList = hs.clientHello.cipherSuites
316 } else {
317 preferenceList = hs.clientHello.cipherSuites
318 supportedList = config.cipherSuites()
319 }
320
321 for _, id := range preferenceList {
322 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, supportedCurve, ecdsaOk, pskOk); hs.suite != nil {
323 break
324 }
325 }
326
327 if hs.suite == nil {
328 c.sendAlert(alertHandshakeFailure)
329 return errors.New("tls: no cipher suite supported by both client and server")
330 }
331
332 hs.hello.cipherSuite = hs.suite.id
Steven Valdez0ee2e112016-07-15 06:51:15 -0400333 if c.config.Bugs.SendCipherSuite != 0 {
334 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
335 }
336
Nick Harper728eed82016-07-07 17:36:52 -0700337 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
338 hs.finishedHash.discardHandshakeBuffer()
339 hs.writeClientHash(hs.clientHello.marshal())
340
341 // Resolve PSK and compute the early secret.
David Benjaminc87ebde2016-07-13 17:26:02 -0400342 // TODO(davidben): Implement PSK in TLS 1.3.
343 psk := hs.finishedHash.zeroSecret()
344 hs.finishedHash.setResumptionContext(hs.finishedHash.zeroSecret())
Nick Harper728eed82016-07-07 17:36:52 -0700345
346 earlySecret := hs.finishedHash.extractKey(hs.finishedHash.zeroSecret(), psk)
347
348 // Resolve ECDHE and compute the handshake secret.
349 var ecdheSecret []byte
Steven Valdez143e8b32016-07-11 13:19:03 -0400350 if hs.suite.flags&suiteECDHE != 0 && !config.Bugs.MissingKeyShare {
Nick Harper728eed82016-07-07 17:36:52 -0700351 // Look for the key share corresponding to our selected curve.
352 var selectedKeyShare *keyShareEntry
353 for i := range hs.clientHello.keyShares {
354 if hs.clientHello.keyShares[i].group == selectedCurve {
355 selectedKeyShare = &hs.clientHello.keyShares[i]
356 break
357 }
358 }
359
Steven Valdez5440fe02016-07-18 12:40:30 -0400360 sendHelloRetryRequest := selectedKeyShare == nil
361 if config.Bugs.UnnecessaryHelloRetryRequest {
362 sendHelloRetryRequest = true
363 }
364 if config.Bugs.SkipHelloRetryRequest {
365 sendHelloRetryRequest = false
366 }
367 if sendHelloRetryRequest {
368 firstTime := true
369 ResendHelloRetryRequest:
Nick Harperdcfbc672016-07-16 17:47:31 +0200370 // Send HelloRetryRequest.
371 helloRetryRequestMsg := helloRetryRequestMsg{
372 vers: c.vers,
373 cipherSuite: hs.hello.cipherSuite,
374 selectedGroup: selectedCurve,
375 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400376 if config.Bugs.SendHelloRetryRequestCurve != 0 {
377 helloRetryRequestMsg.selectedGroup = config.Bugs.SendHelloRetryRequestCurve
378 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200379 hs.writeServerHash(helloRetryRequestMsg.marshal())
380 c.writeRecord(recordTypeHandshake, helloRetryRequestMsg.marshal())
381
382 // Read new ClientHello.
383 newMsg, err := c.readHandshake()
384 if err != nil {
385 return err
386 }
387 newClientHello, ok := newMsg.(*clientHelloMsg)
388 if !ok {
389 c.sendAlert(alertUnexpectedMessage)
390 return unexpectedMessageError(newClientHello, newMsg)
391 }
392 hs.writeClientHash(newClientHello.marshal())
393
394 // Check that the new ClientHello matches the old ClientHello, except for
395 // the addition of the new KeyShareEntry at the end of the list, and
396 // removing the EarlyDataIndication extension (if present).
397 newKeyShares := newClientHello.keyShares
398 if len(newKeyShares) == 0 || newKeyShares[len(newKeyShares)-1].group != selectedCurve {
399 return errors.New("tls: KeyShare from HelloRetryRequest not present in new ClientHello")
400 }
401 oldClientHelloCopy := *hs.clientHello
402 oldClientHelloCopy.raw = nil
403 oldClientHelloCopy.hasEarlyData = false
404 oldClientHelloCopy.earlyDataContext = nil
405 newClientHelloCopy := *newClientHello
406 newClientHelloCopy.raw = nil
407 newClientHelloCopy.keyShares = newKeyShares[:len(newKeyShares)-1]
408 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
409 return errors.New("tls: new ClientHello does not match")
410 }
411
Steven Valdez5440fe02016-07-18 12:40:30 -0400412 if firstTime && config.Bugs.SecondHelloRetryRequest {
413 firstTime = false
414 goto ResendHelloRetryRequest
415 }
416
Nick Harperdcfbc672016-07-16 17:47:31 +0200417 selectedKeyShare = &newKeyShares[len(newKeyShares)-1]
Nick Harper728eed82016-07-07 17:36:52 -0700418 }
419
420 // Once a curve has been selected and a key share identified,
421 // the server needs to generate a public value and send it in
422 // the ServerHello.
Steven Valdez5440fe02016-07-18 12:40:30 -0400423 curve, ok := curveForCurveID(selectedCurve)
Nick Harper728eed82016-07-07 17:36:52 -0700424 if !ok {
425 panic("tls: server failed to look up curve ID")
426 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400427 c.curveID = selectedCurve
428
429 var peerKey []byte
430 if config.Bugs.SkipHelloRetryRequest {
431 // If skipping HelloRetryRequest, use a random key to
432 // avoid crashing.
433 curve2, _ := curveForCurveID(selectedCurve)
434 var err error
435 peerKey, err = curve2.offer(config.rand())
436 if err != nil {
437 return err
438 }
439 } else {
440 peerKey = selectedKeyShare.keyExchange
441 }
442
Nick Harper728eed82016-07-07 17:36:52 -0700443 var publicKey []byte
444 var err error
Steven Valdez5440fe02016-07-18 12:40:30 -0400445 publicKey, ecdheSecret, err = curve.accept(config.rand(), peerKey)
Nick Harper728eed82016-07-07 17:36:52 -0700446 if err != nil {
447 c.sendAlert(alertHandshakeFailure)
448 return err
449 }
450 hs.hello.hasKeyShare = true
Steven Valdez0ee2e112016-07-15 06:51:15 -0400451
Steven Valdez5440fe02016-07-18 12:40:30 -0400452 curveID := selectedCurve
Steven Valdez0ee2e112016-07-15 06:51:15 -0400453 if c.config.Bugs.SendCurve != 0 {
454 curveID = config.Bugs.SendCurve
455 }
456 if c.config.Bugs.InvalidECDHPoint {
457 publicKey[0] ^= 0xff
458 }
459
Nick Harper728eed82016-07-07 17:36:52 -0700460 hs.hello.keyShare = keyShareEntry{
Steven Valdez0ee2e112016-07-15 06:51:15 -0400461 group: curveID,
Nick Harper728eed82016-07-07 17:36:52 -0700462 keyExchange: publicKey,
463 }
Steven Valdez143e8b32016-07-11 13:19:03 -0400464
465 if config.Bugs.EncryptedExtensionsWithKeyShare {
466 encryptedExtensions.extensions.hasKeyShare = true
467 encryptedExtensions.extensions.keyShare = keyShareEntry{
468 group: curveID,
469 keyExchange: publicKey,
470 }
471 }
Nick Harper728eed82016-07-07 17:36:52 -0700472 } else {
473 ecdheSecret = hs.finishedHash.zeroSecret()
474 }
475
476 // Send unencrypted ServerHello.
477 hs.writeServerHash(hs.hello.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400478 if config.Bugs.PartialEncryptedExtensionsWithServerHello {
479 helloBytes := hs.hello.marshal()
480 toWrite := make([]byte, 0, len(helloBytes)+1)
481 toWrite = append(toWrite, helloBytes...)
482 toWrite = append(toWrite, typeEncryptedExtensions)
483 c.writeRecord(recordTypeHandshake, toWrite)
484 } else {
485 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
486 }
Nick Harper728eed82016-07-07 17:36:52 -0700487 c.flushHandshake()
488
489 // Compute the handshake secret.
490 handshakeSecret := hs.finishedHash.extractKey(earlySecret, ecdheSecret)
491
492 // Switch to handshake traffic keys.
493 handshakeTrafficSecret := hs.finishedHash.deriveSecret(handshakeSecret, handshakeTrafficLabel)
David Benjamin21c00282016-07-18 21:56:23 +0200494 c.out.useTrafficSecret(c.vers, hs.suite, handshakeTrafficSecret, handshakePhase, serverWrite)
495 c.in.useTrafficSecret(c.vers, hs.suite, handshakeTrafficSecret, handshakePhase, clientWrite)
Nick Harper728eed82016-07-07 17:36:52 -0700496
David Benjamin615119a2016-07-06 19:22:55 -0700497 if hs.suite.flags&suitePSK != 0 {
David Benjaminc87ebde2016-07-13 17:26:02 -0400498 return errors.New("tls: PSK ciphers not implemented for TLS 1.3")
499 } else {
David Benjamin615119a2016-07-06 19:22:55 -0700500 if hs.clientHello.ocspStapling {
501 encryptedExtensions.extensions.ocspResponse = hs.cert.OCSPStaple
502 }
503 if hs.clientHello.sctListSupported {
504 encryptedExtensions.extensions.sctList = hs.cert.SignedCertificateTimestampList
505 }
506 }
507
Nick Harper728eed82016-07-07 17:36:52 -0700508 // Send EncryptedExtensions.
509 hs.writeServerHash(encryptedExtensions.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400510 if config.Bugs.PartialEncryptedExtensionsWithServerHello {
511 // The first byte has already been sent.
512 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()[1:])
513 } else {
514 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal())
515 }
Nick Harper728eed82016-07-07 17:36:52 -0700516
517 if hs.suite.flags&suitePSK == 0 {
518 if config.ClientAuth >= RequestClientCert {
David Benjamin8d343b42016-07-09 14:26:01 -0700519 // Request a client certificate
520 certReq := &certificateRequestMsg{
521 hasSignatureAlgorithm: true,
522 hasRequestContext: true,
523 }
524 if !config.Bugs.NoSignatureAlgorithms {
David Benjaminf74ec792016-07-13 21:18:49 -0400525 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin8d343b42016-07-09 14:26:01 -0700526 }
527
528 // An empty list of certificateAuthorities signals to
529 // the client that it may send any certificate in response
530 // to our request. When we know the CAs we trust, then
531 // we can send them down, so that the client can choose
532 // an appropriate certificate to give to us.
533 if config.ClientCAs != nil {
534 certReq.certificateAuthorities = config.ClientCAs.Subjects()
535 }
536 hs.writeServerHash(certReq.marshal())
537 c.writeRecord(recordTypeHandshake, certReq.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700538 }
539
540 certMsg := &certificateMsg{
541 hasRequestContext: true,
542 }
543 if !config.Bugs.EmptyCertificateList {
544 certMsg.certificates = hs.cert.Certificate
545 }
David Benjamin1edae6b2016-07-13 16:58:23 -0400546 certMsgBytes := certMsg.marshal()
David Benjamin1edae6b2016-07-13 16:58:23 -0400547 hs.writeServerHash(certMsgBytes)
548 c.writeRecord(recordTypeHandshake, certMsgBytes)
Nick Harper728eed82016-07-07 17:36:52 -0700549
550 certVerify := &certificateVerifyMsg{
551 hasSignatureAlgorithm: true,
552 }
553
554 // Determine the hash to sign.
555 privKey := hs.cert.PrivateKey
556
557 var err error
558 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, config, hs.clientHello.signatureAlgorithms)
559 if err != nil {
560 c.sendAlert(alertInternalError)
561 return err
562 }
563
564 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
565 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
566 if err != nil {
567 c.sendAlert(alertInternalError)
568 return err
569 }
570
Steven Valdez0ee2e112016-07-15 06:51:15 -0400571 if config.Bugs.SendSignatureAlgorithm != 0 {
572 certVerify.signatureAlgorithm = config.Bugs.SendSignatureAlgorithm
573 }
574
Nick Harper728eed82016-07-07 17:36:52 -0700575 hs.writeServerHash(certVerify.marshal())
576 c.writeRecord(recordTypeHandshake, certVerify.marshal())
577 }
578
579 finished := new(finishedMsg)
580 finished.verifyData = hs.finishedHash.serverSum(handshakeTrafficSecret)
581 if config.Bugs.BadFinished {
582 finished.verifyData[0]++
583 }
584 hs.writeServerHash(finished.marshal())
585 c.writeRecord(recordTypeHandshake, finished.marshal())
David Benjamin02edcd02016-07-27 17:40:37 -0400586 if c.config.Bugs.SendExtraFinished {
587 c.writeRecord(recordTypeHandshake, finished.marshal())
588 }
Nick Harper728eed82016-07-07 17:36:52 -0700589 c.flushHandshake()
590
591 // The various secrets do not incorporate the client's final leg, so
592 // derive them now before updating the handshake context.
593 masterSecret := hs.finishedHash.extractKey(handshakeSecret, hs.finishedHash.zeroSecret())
594 trafficSecret := hs.finishedHash.deriveSecret(masterSecret, applicationTrafficLabel)
595
David Benjamin2aad4062016-07-14 23:15:40 -0400596 // Switch to application data keys on write. In particular, any alerts
597 // from the client certificate are sent over these keys.
David Benjamin21c00282016-07-18 21:56:23 +0200598 c.out.useTrafficSecret(c.vers, hs.suite, trafficSecret, applicationPhase, serverWrite)
David Benjamin2aad4062016-07-14 23:15:40 -0400599
Nick Harper728eed82016-07-07 17:36:52 -0700600 // If we requested a client certificate, then the client must send a
601 // certificate message, even if it's empty.
602 if config.ClientAuth >= RequestClientCert {
David Benjamin8d343b42016-07-09 14:26:01 -0700603 msg, err := c.readHandshake()
604 if err != nil {
605 return err
606 }
607
608 certMsg, ok := msg.(*certificateMsg)
609 if !ok {
610 c.sendAlert(alertUnexpectedMessage)
611 return unexpectedMessageError(certMsg, msg)
612 }
613 hs.writeClientHash(certMsg.marshal())
614
615 if len(certMsg.certificates) == 0 {
616 // The client didn't actually send a certificate
617 switch config.ClientAuth {
618 case RequireAnyClientCert, RequireAndVerifyClientCert:
619 c.sendAlert(alertBadCertificate)
620 return errors.New("tls: client didn't provide a certificate")
621 }
622 }
623
624 pub, err := hs.processCertsFromClient(certMsg.certificates)
625 if err != nil {
626 return err
627 }
628
629 if len(c.peerCertificates) > 0 {
630 msg, err = c.readHandshake()
631 if err != nil {
632 return err
633 }
634
635 certVerify, ok := msg.(*certificateVerifyMsg)
636 if !ok {
637 c.sendAlert(alertUnexpectedMessage)
638 return unexpectedMessageError(certVerify, msg)
639 }
640
David Benjaminf74ec792016-07-13 21:18:49 -0400641 c.peerSignatureAlgorithm = certVerify.signatureAlgorithm
David Benjamin8d343b42016-07-09 14:26:01 -0700642 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
643 if err := verifyMessage(c.vers, pub, config, certVerify.signatureAlgorithm, input, certVerify.signature); err != nil {
644 c.sendAlert(alertBadCertificate)
645 return err
646 }
647 hs.writeClientHash(certVerify.marshal())
648 }
Nick Harper728eed82016-07-07 17:36:52 -0700649 }
650
651 // Read the client Finished message.
652 msg, err := c.readHandshake()
653 if err != nil {
654 return err
655 }
656 clientFinished, ok := msg.(*finishedMsg)
657 if !ok {
658 c.sendAlert(alertUnexpectedMessage)
659 return unexpectedMessageError(clientFinished, msg)
660 }
661
662 verify := hs.finishedHash.clientSum(handshakeTrafficSecret)
663 if len(verify) != len(clientFinished.verifyData) ||
664 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
665 c.sendAlert(alertHandshakeFailure)
666 return errors.New("tls: client's Finished message was incorrect")
667 }
David Benjamin97a0a082016-07-13 17:57:35 -0400668 hs.writeClientHash(clientFinished.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700669
David Benjamin2aad4062016-07-14 23:15:40 -0400670 // Switch to application data keys on read.
David Benjamin21c00282016-07-18 21:56:23 +0200671 c.in.useTrafficSecret(c.vers, hs.suite, trafficSecret, applicationPhase, clientWrite)
Nick Harper728eed82016-07-07 17:36:52 -0700672
Nick Harper728eed82016-07-07 17:36:52 -0700673 c.cipherSuite = hs.suite
David Benjamin97a0a082016-07-13 17:57:35 -0400674 c.exporterSecret = hs.finishedHash.deriveSecret(masterSecret, exporterLabel)
David Benjamin58104882016-07-18 01:25:41 +0200675 c.resumptionSecret = hs.finishedHash.deriveSecret(masterSecret, resumptionLabel)
676
677 // TODO(davidben): Allow configuring the number of tickets sent for
678 // testing.
679 if !c.config.SessionTicketsDisabled {
680 ticketCount := 2
681 for i := 0; i < ticketCount; i++ {
682 c.SendNewSessionTicket()
683 }
684 }
Nick Harper728eed82016-07-07 17:36:52 -0700685 return nil
686}
687
David Benjaminf25dda92016-07-04 10:05:26 -0700688// processClientHello processes the ClientHello message from the client and
689// decides whether we will perform session resumption.
690func (hs *serverHandshakeState) processClientHello() (isResume bool, err error) {
691 config := hs.c.config
692 c := hs.c
693
694 hs.hello = &serverHelloMsg{
695 isDTLS: c.isDTLS,
696 vers: c.vers,
697 compressionMethod: compressionNone,
698 }
699
Steven Valdez5440fe02016-07-18 12:40:30 -0400700 if config.Bugs.SendServerHelloVersion != 0 {
701 hs.hello.vers = config.Bugs.SendServerHelloVersion
702 }
703
David Benjaminf25dda92016-07-04 10:05:26 -0700704 hs.hello.random = make([]byte, 32)
705 _, err = io.ReadFull(config.rand(), hs.hello.random)
706 if err != nil {
707 c.sendAlert(alertInternalError)
708 return false, err
709 }
David Benjamin1f61f0d2016-07-10 12:20:35 -0400710 // Signal downgrades in the server random, per draft-ietf-tls-tls13-14,
711 // section 6.3.1.2.
Nick Harper85f20c22016-07-04 10:11:59 -0700712 if c.vers <= VersionTLS12 && config.maxVersion(c.isDTLS) >= VersionTLS13 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400713 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS13)
Nick Harper85f20c22016-07-04 10:11:59 -0700714 }
715 if c.vers <= VersionTLS11 && config.maxVersion(c.isDTLS) == VersionTLS12 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400716 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS12)
Nick Harper85f20c22016-07-04 10:11:59 -0700717 }
David Benjaminf25dda92016-07-04 10:05:26 -0700718
719 foundCompression := false
720 // We only support null compression, so check that the client offered it.
721 for _, compression := range hs.clientHello.compressionMethods {
722 if compression == compressionNone {
723 foundCompression = true
724 break
725 }
726 }
727
728 if !foundCompression {
729 c.sendAlert(alertHandshakeFailure)
730 return false, errors.New("tls: client does not support uncompressed connections")
731 }
David Benjamin7d79f832016-07-04 09:20:45 -0700732
733 if err := hs.processClientExtensions(&hs.hello.extensions); err != nil {
734 return false, err
Adam Langley09505632015-07-30 18:10:13 -0700735 }
Adam Langley95c29f32014-06-20 12:00:00 -0700736
737 supportedCurve := false
738 preferredCurves := config.curvePreferences()
739Curves:
740 for _, curve := range hs.clientHello.supportedCurves {
741 for _, supported := range preferredCurves {
742 if supported == curve {
743 supportedCurve = true
744 break Curves
745 }
746 }
747 }
748
749 supportedPointFormat := false
750 for _, pointFormat := range hs.clientHello.supportedPoints {
751 if pointFormat == pointFormatUncompressed {
752 supportedPointFormat = true
753 break
754 }
755 }
756 hs.ellipticOk = supportedCurve && supportedPointFormat
757
Adam Langley95c29f32014-06-20 12:00:00 -0700758 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
759
David Benjamin4b27d9f2015-05-12 22:42:52 -0400760 // For test purposes, check that the peer never offers a session when
761 // renegotiating.
762 if c.cipherSuite != nil && len(hs.clientHello.sessionId) > 0 && c.config.Bugs.FailIfResumeOnRenego {
763 return false, errors.New("tls: offered resumption on renegotiation")
764 }
765
David Benjamindd6fed92015-10-23 17:41:12 -0400766 if c.config.Bugs.FailIfSessionOffered && (len(hs.clientHello.sessionTicket) > 0 || len(hs.clientHello.sessionId) > 0) {
767 return false, errors.New("tls: client offered a session ticket or ID")
768 }
769
Adam Langley95c29f32014-06-20 12:00:00 -0700770 if hs.checkForResumption() {
771 return true, nil
772 }
773
Adam Langley95c29f32014-06-20 12:00:00 -0700774 var preferenceList, supportedList []uint16
775 if c.config.PreferServerCipherSuites {
776 preferenceList = c.config.cipherSuites()
777 supportedList = hs.clientHello.cipherSuites
778 } else {
779 preferenceList = hs.clientHello.cipherSuites
780 supportedList = c.config.cipherSuites()
781 }
782
783 for _, id := range preferenceList {
Nick Harper728eed82016-07-07 17:36:52 -0700784 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk, true); hs.suite != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700785 break
786 }
787 }
788
789 if hs.suite == nil {
790 c.sendAlert(alertHandshakeFailure)
791 return false, errors.New("tls: no cipher suite supported by both client and server")
792 }
793
794 return false, nil
795}
796
David Benjamin7d79f832016-07-04 09:20:45 -0700797// processClientExtensions processes all ClientHello extensions not directly
798// related to cipher suite negotiation and writes responses in serverExtensions.
799func (hs *serverHandshakeState) processClientExtensions(serverExtensions *serverExtensions) error {
800 config := hs.c.config
801 c := hs.c
802
David Benjamin8d315d72016-07-18 01:03:18 +0200803 if c.vers < VersionTLS13 || config.Bugs.NegotiateRenegotiationInfoAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700804 if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) {
805 c.sendAlert(alertHandshakeFailure)
806 return errors.New("tls: renegotiation mismatch")
David Benjamin7d79f832016-07-04 09:20:45 -0700807 }
David Benjamin7d79f832016-07-04 09:20:45 -0700808
Nick Harper728eed82016-07-07 17:36:52 -0700809 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
810 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.clientVerify...)
811 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.serverVerify...)
812 if c.config.Bugs.BadRenegotiationInfo {
813 serverExtensions.secureRenegotiation[0] ^= 0x80
814 }
815 } else {
816 serverExtensions.secureRenegotiation = hs.clientHello.secureRenegotiation
817 }
818
819 if c.noRenegotiationInfo() {
820 serverExtensions.secureRenegotiation = nil
821 }
David Benjamin7d79f832016-07-04 09:20:45 -0700822 }
823
824 serverExtensions.duplicateExtension = c.config.Bugs.DuplicateExtension
825
826 if len(hs.clientHello.serverName) > 0 {
827 c.serverName = hs.clientHello.serverName
828 }
829 if len(config.Certificates) == 0 {
830 c.sendAlert(alertInternalError)
831 return errors.New("tls: no certificates configured")
832 }
833 hs.cert = &config.Certificates[0]
834 if len(hs.clientHello.serverName) > 0 {
835 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
836 }
837 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
838 return errors.New("tls: unexpected server name")
839 }
840
841 if len(hs.clientHello.alpnProtocols) > 0 {
842 if proto := c.config.Bugs.ALPNProtocol; proto != nil {
843 serverExtensions.alpnProtocol = *proto
844 serverExtensions.alpnProtocolEmpty = len(*proto) == 0
845 c.clientProtocol = *proto
846 c.usedALPN = true
847 } else if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
848 serverExtensions.alpnProtocol = selectedProto
849 c.clientProtocol = selectedProto
850 c.usedALPN = true
851 }
852 }
Nick Harper728eed82016-07-07 17:36:52 -0700853
David Benjamin0c40a962016-08-01 12:05:50 -0400854 if len(c.config.Bugs.SendALPN) > 0 {
855 serverExtensions.alpnProtocol = c.config.Bugs.SendALPN
856 }
857
David Benjamin8d315d72016-07-18 01:03:18 +0200858 if c.vers < VersionTLS13 || config.Bugs.NegotiateNPNAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700859 if len(hs.clientHello.alpnProtocols) == 0 || c.config.Bugs.NegotiateALPNAndNPN {
860 // Although sending an empty NPN extension is reasonable, Firefox has
861 // had a bug around this. Best to send nothing at all if
862 // config.NextProtos is empty. See
863 // https://code.google.com/p/go/issues/detail?id=5445.
864 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
865 serverExtensions.nextProtoNeg = true
866 serverExtensions.nextProtos = config.NextProtos
867 serverExtensions.npnLast = config.Bugs.SwapNPNAndALPN
868 }
David Benjamin7d79f832016-07-04 09:20:45 -0700869 }
Steven Valdez143e8b32016-07-11 13:19:03 -0400870 }
David Benjamin7d79f832016-07-04 09:20:45 -0700871
David Benjamin8d315d72016-07-18 01:03:18 +0200872 if c.vers < VersionTLS13 || config.Bugs.NegotiateEMSAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700873 serverExtensions.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !c.config.Bugs.NoExtendedMasterSecret
Steven Valdez143e8b32016-07-11 13:19:03 -0400874 }
David Benjamin7d79f832016-07-04 09:20:45 -0700875
David Benjamin8d315d72016-07-18 01:03:18 +0200876 if c.vers < VersionTLS13 || config.Bugs.NegotiateChannelIDAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700877 if hs.clientHello.channelIDSupported && config.RequestChannelID {
878 serverExtensions.channelIDRequested = true
879 }
David Benjamin7d79f832016-07-04 09:20:45 -0700880 }
881
882 if hs.clientHello.srtpProtectionProfiles != nil {
883 SRTPLoop:
884 for _, p1 := range c.config.SRTPProtectionProfiles {
885 for _, p2 := range hs.clientHello.srtpProtectionProfiles {
886 if p1 == p2 {
887 serverExtensions.srtpProtectionProfile = p1
888 c.srtpProtectionProfile = p1
889 break SRTPLoop
890 }
891 }
892 }
893 }
894
895 if c.config.Bugs.SendSRTPProtectionProfile != 0 {
896 serverExtensions.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
897 }
898
899 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
900 if hs.clientHello.customExtension != *expected {
901 return fmt.Errorf("tls: bad custom extension contents %q", hs.clientHello.customExtension)
902 }
903 }
904 serverExtensions.customExtension = config.Bugs.CustomExtension
905
Steven Valdez143e8b32016-07-11 13:19:03 -0400906 if c.config.Bugs.AdvertiseTicketExtension {
907 serverExtensions.ticketSupported = true
908 }
909
David Benjamin7d79f832016-07-04 09:20:45 -0700910 return nil
911}
912
Adam Langley95c29f32014-06-20 12:00:00 -0700913// checkForResumption returns true if we should perform resumption on this connection.
914func (hs *serverHandshakeState) checkForResumption() bool {
915 c := hs.c
916
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500917 if len(hs.clientHello.sessionTicket) > 0 {
918 if c.config.SessionTicketsDisabled {
919 return false
920 }
David Benjaminb0c8db72014-09-24 15:19:56 -0400921
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500922 var ok bool
923 if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
924 return false
925 }
926 } else {
927 if c.config.ServerSessionCache == nil {
928 return false
929 }
930
931 var ok bool
932 sessionId := string(hs.clientHello.sessionId)
933 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
934 return false
935 }
Adam Langley95c29f32014-06-20 12:00:00 -0700936 }
937
David Benjamine18d8212014-11-10 02:37:15 -0500938 // Never resume a session for a different SSL version.
939 if !c.config.Bugs.AllowSessionVersionMismatch && c.vers != hs.sessionState.vers {
940 return false
Adam Langley95c29f32014-06-20 12:00:00 -0700941 }
942
943 cipherSuiteOk := false
944 // Check that the client is still offering the ciphersuite in the session.
945 for _, id := range hs.clientHello.cipherSuites {
946 if id == hs.sessionState.cipherSuite {
947 cipherSuiteOk = true
948 break
949 }
950 }
951 if !cipherSuiteOk {
952 return false
953 }
954
955 // Check that we also support the ciphersuite from the session.
Nick Harper728eed82016-07-07 17:36:52 -0700956 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 -0700957 if hs.suite == nil {
958 return false
959 }
960
961 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
962 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
963 if needClientCerts && !sessionHasClientCerts {
964 return false
965 }
966 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
967 return false
968 }
969
970 return true
971}
972
973func (hs *serverHandshakeState) doResumeHandshake() error {
974 c := hs.c
975
976 hs.hello.cipherSuite = hs.suite.id
David Benjaminece3de92015-03-16 18:02:20 -0400977 if c.config.Bugs.SendCipherSuite != 0 {
978 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
979 }
Adam Langley95c29f32014-06-20 12:00:00 -0700980 // We echo the client's session ID in the ServerHello to let it know
981 // that we're doing a resumption.
982 hs.hello.sessionId = hs.clientHello.sessionId
Nick Harperb3d51be2016-07-01 11:43:18 -0400983 hs.hello.extensions.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -0700984
David Benjamin80d1b352016-05-04 19:19:06 -0400985 if c.config.Bugs.SendSCTListOnResume != nil {
Nick Harperb3d51be2016-07-01 11:43:18 -0400986 hs.hello.extensions.sctList = c.config.Bugs.SendSCTListOnResume
David Benjamin80d1b352016-05-04 19:19:06 -0400987 }
988
Adam Langley95c29f32014-06-20 12:00:00 -0700989 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -0400990 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -0400991 hs.writeClientHash(hs.clientHello.marshal())
992 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700993
994 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
995
996 if len(hs.sessionState.certificates) > 0 {
997 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
998 return err
999 }
1000 }
1001
1002 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -07001003 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -07001004
1005 return nil
1006}
1007
1008func (hs *serverHandshakeState) doFullHandshake() error {
1009 config := hs.c.config
1010 c := hs.c
1011
David Benjamin48cae082014-10-27 01:06:24 -04001012 isPSK := hs.suite.flags&suitePSK != 0
1013 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001014 hs.hello.extensions.ocspStapling = true
Adam Langley95c29f32014-06-20 12:00:00 -07001015 }
1016
David Benjamin61f95272014-11-25 01:55:35 -05001017 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001018 hs.hello.extensions.sctList = hs.cert.SignedCertificateTimestampList
David Benjamin61f95272014-11-25 01:55:35 -05001019 }
1020
Nick Harperb3d51be2016-07-01 11:43:18 -04001021 hs.hello.extensions.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
Adam Langley95c29f32014-06-20 12:00:00 -07001022 hs.hello.cipherSuite = hs.suite.id
David Benjamin6095de82014-12-27 01:50:38 -05001023 if config.Bugs.SendCipherSuite != 0 {
1024 hs.hello.cipherSuite = config.Bugs.SendCipherSuite
1025 }
Nick Harperb3d51be2016-07-01 11:43:18 -04001026 c.extendedMasterSecret = hs.hello.extensions.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -07001027
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001028 // Generate a session ID if we're to save the session.
Nick Harperb3d51be2016-07-01 11:43:18 -04001029 if !hs.hello.extensions.ticketSupported && config.ServerSessionCache != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001030 hs.hello.sessionId = make([]byte, 32)
1031 if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
1032 c.sendAlert(alertInternalError)
1033 return errors.New("tls: short read from Rand: " + err.Error())
1034 }
1035 }
1036
Adam Langley95c29f32014-06-20 12:00:00 -07001037 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -04001038 hs.writeClientHash(hs.clientHello.marshal())
1039 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001040
1041 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
1042
David Benjamin48cae082014-10-27 01:06:24 -04001043 if !isPSK {
1044 certMsg := new(certificateMsg)
David Benjamin8923c0b2015-06-07 11:42:34 -04001045 if !config.Bugs.EmptyCertificateList {
1046 certMsg.certificates = hs.cert.Certificate
1047 }
David Benjamin48cae082014-10-27 01:06:24 -04001048 if !config.Bugs.UnauthenticatedECDH {
David Benjaminbcb2d912015-02-24 23:45:43 -05001049 certMsgBytes := certMsg.marshal()
David Benjaminbcb2d912015-02-24 23:45:43 -05001050 hs.writeServerHash(certMsgBytes)
1051 c.writeRecord(recordTypeHandshake, certMsgBytes)
David Benjamin48cae082014-10-27 01:06:24 -04001052 }
David Benjamin1c375dd2014-07-12 00:48:23 -04001053 }
Adam Langley95c29f32014-06-20 12:00:00 -07001054
Nick Harperb3d51be2016-07-01 11:43:18 -04001055 if hs.hello.extensions.ocspStapling && !c.config.Bugs.SkipCertificateStatus {
Adam Langley95c29f32014-06-20 12:00:00 -07001056 certStatus := new(certificateStatusMsg)
1057 certStatus.statusType = statusTypeOCSP
1058 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -04001059 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001060 c.writeRecord(recordTypeHandshake, certStatus.marshal())
1061 }
1062
1063 keyAgreement := hs.suite.ka(c.vers)
1064 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
1065 if err != nil {
1066 c.sendAlert(alertHandshakeFailure)
1067 return err
1068 }
Steven Valdez5440fe02016-07-18 12:40:30 -04001069 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
1070 c.curveID = ecdhe.curveID
1071 }
David Benjamin9c651c92014-07-12 13:27:45 -04001072 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -04001073 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001074 c.writeRecord(recordTypeHandshake, skx.marshal())
1075 }
1076
1077 if config.ClientAuth >= RequestClientCert {
1078 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -04001079 certReq := &certificateRequestMsg{
1080 certificateTypes: config.ClientCertificateTypes,
1081 }
1082 if certReq.certificateTypes == nil {
1083 certReq.certificateTypes = []byte{
1084 byte(CertTypeRSASign),
1085 byte(CertTypeECDSASign),
1086 }
Adam Langley95c29f32014-06-20 12:00:00 -07001087 }
1088 if c.vers >= VersionTLS12 {
Nick Harper60edffd2016-06-21 15:19:24 -07001089 certReq.hasSignatureAlgorithm = true
1090 if !config.Bugs.NoSignatureAlgorithms {
David Benjamin7a41d372016-07-09 11:21:54 -07001091 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin000800a2014-11-14 01:43:59 -05001092 }
Adam Langley95c29f32014-06-20 12:00:00 -07001093 }
1094
1095 // An empty list of certificateAuthorities signals to
1096 // the client that it may send any certificate in response
1097 // to our request. When we know the CAs we trust, then
1098 // we can send them down, so that the client can choose
1099 // an appropriate certificate to give to us.
1100 if config.ClientCAs != nil {
1101 certReq.certificateAuthorities = config.ClientCAs.Subjects()
1102 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001103 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001104 c.writeRecord(recordTypeHandshake, certReq.marshal())
1105 }
1106
1107 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001108 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001109 c.writeRecord(recordTypeHandshake, helloDone.marshal())
David Benjamin582ba042016-07-07 12:33:25 -07001110 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001111
1112 var pub crypto.PublicKey // public key for client auth, if any
1113
David Benjamin83f90402015-01-27 01:09:43 -05001114 if err := c.simulatePacketLoss(nil); err != nil {
1115 return err
1116 }
Adam Langley95c29f32014-06-20 12:00:00 -07001117 msg, err := c.readHandshake()
1118 if err != nil {
1119 return err
1120 }
1121
1122 var ok bool
1123 // If we requested a client certificate, then the client must send a
1124 // certificate message, even if it's empty.
1125 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -04001126 var certMsg *certificateMsg
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001127 var certificates [][]byte
1128 if certMsg, ok = msg.(*certificateMsg); ok {
1129 if c.vers == VersionSSL30 && len(certMsg.certificates) == 0 {
1130 return errors.New("tls: empty certificate message in SSL 3.0")
1131 }
1132
1133 hs.writeClientHash(certMsg.marshal())
1134 certificates = certMsg.certificates
1135 } else if c.vers != VersionSSL30 {
1136 // In TLS, the Certificate message is required. In SSL
1137 // 3.0, the peer skips it when sending no certificates.
Adam Langley95c29f32014-06-20 12:00:00 -07001138 c.sendAlert(alertUnexpectedMessage)
1139 return unexpectedMessageError(certMsg, msg)
1140 }
Adam Langley95c29f32014-06-20 12:00:00 -07001141
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001142 if len(certificates) == 0 {
Adam Langley95c29f32014-06-20 12:00:00 -07001143 // The client didn't actually send a certificate
1144 switch config.ClientAuth {
1145 case RequireAnyClientCert, RequireAndVerifyClientCert:
1146 c.sendAlert(alertBadCertificate)
1147 return errors.New("tls: client didn't provide a certificate")
1148 }
1149 }
1150
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001151 pub, err = hs.processCertsFromClient(certificates)
Adam Langley95c29f32014-06-20 12:00:00 -07001152 if err != nil {
1153 return err
1154 }
1155
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001156 if ok {
1157 msg, err = c.readHandshake()
1158 if err != nil {
1159 return err
1160 }
Adam Langley95c29f32014-06-20 12:00:00 -07001161 }
1162 }
1163
1164 // Get client key exchange
1165 ckx, ok := msg.(*clientKeyExchangeMsg)
1166 if !ok {
1167 c.sendAlert(alertUnexpectedMessage)
1168 return unexpectedMessageError(ckx, msg)
1169 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001170 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001171
David Benjamine098ec22014-08-27 23:13:20 -04001172 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
1173 if err != nil {
1174 c.sendAlert(alertHandshakeFailure)
1175 return err
1176 }
Adam Langley75712922014-10-10 16:23:43 -07001177 if c.extendedMasterSecret {
1178 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1179 } else {
1180 if c.config.Bugs.RequireExtendedMasterSecret {
1181 return errors.New("tls: extended master secret required but not supported by peer")
1182 }
1183 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
1184 }
David Benjamine098ec22014-08-27 23:13:20 -04001185
Adam Langley95c29f32014-06-20 12:00:00 -07001186 // If we received a client cert in response to our certificate request message,
1187 // the client will send us a certificateVerifyMsg immediately after the
1188 // clientKeyExchangeMsg. This message is a digest of all preceding
1189 // handshake-layer messages that is signed using the private key corresponding
1190 // to the client's certificate. This allows us to verify that the client is in
1191 // possession of the private key of the certificate.
1192 if len(c.peerCertificates) > 0 {
1193 msg, err = c.readHandshake()
1194 if err != nil {
1195 return err
1196 }
1197 certVerify, ok := msg.(*certificateVerifyMsg)
1198 if !ok {
1199 c.sendAlert(alertUnexpectedMessage)
1200 return unexpectedMessageError(certVerify, msg)
1201 }
1202
David Benjaminde620d92014-07-18 15:03:41 -04001203 // Determine the signature type.
Nick Harper60edffd2016-06-21 15:19:24 -07001204 var sigAlg signatureAlgorithm
1205 if certVerify.hasSignatureAlgorithm {
1206 sigAlg = certVerify.signatureAlgorithm
Nick Harper60edffd2016-06-21 15:19:24 -07001207 c.peerSignatureAlgorithm = sigAlg
David Benjaminde620d92014-07-18 15:03:41 -04001208 }
1209
Nick Harper60edffd2016-06-21 15:19:24 -07001210 if c.vers > VersionSSL30 {
David Benjamin1fb125c2016-07-08 18:52:12 -07001211 err = verifyMessage(c.vers, pub, c.config, sigAlg, hs.finishedHash.buffer, certVerify.signature)
Nick Harper60edffd2016-06-21 15:19:24 -07001212 } else {
1213 // SSL 3.0's client certificate construction is
1214 // incompatible with signatureAlgorithm.
1215 rsaPub, ok := pub.(*rsa.PublicKey)
1216 if !ok {
1217 err = errors.New("unsupported key type for client certificate")
1218 } else {
1219 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
1220 err = rsa.VerifyPKCS1v15(rsaPub, crypto.MD5SHA1, digest, certVerify.signature)
David Benjaminde620d92014-07-18 15:03:41 -04001221 }
Adam Langley95c29f32014-06-20 12:00:00 -07001222 }
1223 if err != nil {
1224 c.sendAlert(alertBadCertificate)
1225 return errors.New("could not validate signature of connection nonces: " + err.Error())
1226 }
1227
David Benjamin83c0bc92014-08-04 01:23:53 -04001228 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001229 }
1230
David Benjamine098ec22014-08-27 23:13:20 -04001231 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001232
1233 return nil
1234}
1235
1236func (hs *serverHandshakeState) establishKeys() error {
1237 c := hs.c
1238
1239 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001240 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 -07001241
1242 var clientCipher, serverCipher interface{}
1243 var clientHash, serverHash macFunction
1244
1245 if hs.suite.aead == nil {
1246 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
1247 clientHash = hs.suite.mac(c.vers, clientMAC)
1248 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
1249 serverHash = hs.suite.mac(c.vers, serverMAC)
1250 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001251 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1252 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001253 }
1254
1255 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
1256 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
1257
1258 return nil
1259}
1260
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001261func (hs *serverHandshakeState) readFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001262 c := hs.c
1263
1264 c.readRecord(recordTypeChangeCipherSpec)
1265 if err := c.in.error(); err != nil {
1266 return err
1267 }
1268
Nick Harperb3d51be2016-07-01 11:43:18 -04001269 if hs.hello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001270 msg, err := c.readHandshake()
1271 if err != nil {
1272 return err
1273 }
1274 nextProto, ok := msg.(*nextProtoMsg)
1275 if !ok {
1276 c.sendAlert(alertUnexpectedMessage)
1277 return unexpectedMessageError(nextProto, msg)
1278 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001279 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001280 c.clientProtocol = nextProto.proto
1281 }
1282
Nick Harperb3d51be2016-07-01 11:43:18 -04001283 if hs.hello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001284 msg, err := c.readHandshake()
1285 if err != nil {
1286 return err
1287 }
David Benjamin24599a82016-06-30 18:56:53 -04001288 channelIDMsg, ok := msg.(*channelIDMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001289 if !ok {
1290 c.sendAlert(alertUnexpectedMessage)
David Benjamin24599a82016-06-30 18:56:53 -04001291 return unexpectedMessageError(channelIDMsg, msg)
David Benjamind30a9902014-08-24 01:44:23 -04001292 }
David Benjamin24599a82016-06-30 18:56:53 -04001293 x := new(big.Int).SetBytes(channelIDMsg.channelID[0:32])
1294 y := new(big.Int).SetBytes(channelIDMsg.channelID[32:64])
1295 r := new(big.Int).SetBytes(channelIDMsg.channelID[64:96])
1296 s := new(big.Int).SetBytes(channelIDMsg.channelID[96:128])
David Benjamind30a9902014-08-24 01:44:23 -04001297 if !elliptic.P256().IsOnCurve(x, y) {
1298 return errors.New("tls: invalid channel ID public key")
1299 }
1300 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
1301 var resumeHash []byte
1302 if isResume {
1303 resumeHash = hs.sessionState.handshakeHash
1304 }
1305 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
1306 return errors.New("tls: invalid channel ID signature")
1307 }
1308 c.channelID = channelID
1309
David Benjamin24599a82016-06-30 18:56:53 -04001310 hs.writeClientHash(channelIDMsg.marshal())
David Benjamind30a9902014-08-24 01:44:23 -04001311 }
1312
Adam Langley95c29f32014-06-20 12:00:00 -07001313 msg, err := c.readHandshake()
1314 if err != nil {
1315 return err
1316 }
1317 clientFinished, ok := msg.(*finishedMsg)
1318 if !ok {
1319 c.sendAlert(alertUnexpectedMessage)
1320 return unexpectedMessageError(clientFinished, msg)
1321 }
1322
1323 verify := hs.finishedHash.clientSum(hs.masterSecret)
1324 if len(verify) != len(clientFinished.verifyData) ||
1325 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
1326 c.sendAlert(alertHandshakeFailure)
1327 return errors.New("tls: client's Finished message is incorrect")
1328 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001329 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001330 copy(out, clientFinished.verifyData)
Adam Langley95c29f32014-06-20 12:00:00 -07001331
David Benjamin83c0bc92014-08-04 01:23:53 -04001332 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001333 return nil
1334}
1335
1336func (hs *serverHandshakeState) sendSessionTicket() error {
Adam Langley95c29f32014-06-20 12:00:00 -07001337 c := hs.c
Adam Langley95c29f32014-06-20 12:00:00 -07001338 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -04001339 vers: c.vers,
1340 cipherSuite: hs.suite.id,
1341 masterSecret: hs.masterSecret,
1342 certificates: hs.certsFromClient,
1343 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -07001344 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001345
Nick Harperb3d51be2016-07-01 11:43:18 -04001346 if !hs.hello.extensions.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001347 if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
1348 c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
1349 }
1350 return nil
1351 }
1352
1353 m := new(newSessionTicketMsg)
1354
David Benjamindd6fed92015-10-23 17:41:12 -04001355 if !c.config.Bugs.SendEmptySessionTicket {
1356 var err error
1357 m.ticket, err = c.encryptTicket(&state)
1358 if err != nil {
1359 return err
1360 }
Adam Langley95c29f32014-06-20 12:00:00 -07001361 }
Adam Langley95c29f32014-06-20 12:00:00 -07001362
David Benjamin83c0bc92014-08-04 01:23:53 -04001363 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001364 c.writeRecord(recordTypeHandshake, m.marshal())
1365
1366 return nil
1367}
1368
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001369func (hs *serverHandshakeState) sendFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001370 c := hs.c
1371
David Benjamin86271ee2014-07-21 16:14:03 -04001372 finished := new(finishedMsg)
1373 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001374 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001375 if c.config.Bugs.BadFinished {
1376 finished.verifyData[0]++
1377 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001378 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001379 hs.finishedBytes = finished.marshal()
1380 hs.writeServerHash(hs.finishedBytes)
1381 postCCSBytes := hs.finishedBytes
David Benjamin86271ee2014-07-21 16:14:03 -04001382
1383 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
1384 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
1385 postCCSBytes = postCCSBytes[5:]
David Benjamin61672812016-07-14 23:10:43 -04001386 } else if c.config.Bugs.SendUnencryptedFinished {
1387 c.writeRecord(recordTypeHandshake, postCCSBytes)
1388 postCCSBytes = nil
David Benjamin86271ee2014-07-21 16:14:03 -04001389 }
David Benjamin582ba042016-07-07 12:33:25 -07001390 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001391
David Benjamina0e52232014-07-19 17:39:58 -04001392 if !c.config.Bugs.SkipChangeCipherSpec {
David Benjamin8411b242015-11-26 12:07:28 -05001393 ccs := []byte{1}
1394 if c.config.Bugs.BadChangeCipherSpec != nil {
1395 ccs = c.config.Bugs.BadChangeCipherSpec
1396 }
1397 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamina0e52232014-07-19 17:39:58 -04001398 }
Adam Langley95c29f32014-06-20 12:00:00 -07001399
David Benjamin4189bd92015-01-25 23:52:39 -05001400 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1401 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1402 }
David Benjamindc3da932015-03-12 15:09:02 -04001403 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1404 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1405 return errors.New("tls: simulating post-CCS alert")
1406 }
David Benjamin4189bd92015-01-25 23:52:39 -05001407
David Benjamin61672812016-07-14 23:10:43 -04001408 if !c.config.Bugs.SkipFinished && len(postCCSBytes) > 0 {
David Benjaminb80168e2015-02-08 18:30:14 -05001409 c.writeRecord(recordTypeHandshake, postCCSBytes)
David Benjamin02edcd02016-07-27 17:40:37 -04001410 if c.config.Bugs.SendExtraFinished {
1411 c.writeRecord(recordTypeHandshake, finished.marshal())
1412 }
1413
David Benjamin12d2c482016-07-24 10:56:51 -04001414 if !c.config.Bugs.PackHelloRequestWithFinished {
1415 // Defer flushing until renegotiation.
1416 c.flushHandshake()
1417 }
David Benjaminb3774b92015-01-31 17:16:01 -05001418 }
Adam Langley95c29f32014-06-20 12:00:00 -07001419
David Benjaminc565ebb2015-04-03 04:06:36 -04001420 c.cipherSuite = hs.suite
Adam Langley95c29f32014-06-20 12:00:00 -07001421
1422 return nil
1423}
1424
1425// processCertsFromClient takes a chain of client certificates either from a
1426// Certificates message or from a sessionState and verifies them. It returns
1427// the public key of the leaf certificate.
1428func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
1429 c := hs.c
1430
1431 hs.certsFromClient = certificates
1432 certs := make([]*x509.Certificate, len(certificates))
1433 var err error
1434 for i, asn1Data := range certificates {
1435 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
1436 c.sendAlert(alertBadCertificate)
1437 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
1438 }
1439 }
1440
1441 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
1442 opts := x509.VerifyOptions{
1443 Roots: c.config.ClientCAs,
1444 CurrentTime: c.config.time(),
1445 Intermediates: x509.NewCertPool(),
1446 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
1447 }
1448
1449 for _, cert := range certs[1:] {
1450 opts.Intermediates.AddCert(cert)
1451 }
1452
1453 chains, err := certs[0].Verify(opts)
1454 if err != nil {
1455 c.sendAlert(alertBadCertificate)
1456 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
1457 }
1458
1459 ok := false
1460 for _, ku := range certs[0].ExtKeyUsage {
1461 if ku == x509.ExtKeyUsageClientAuth {
1462 ok = true
1463 break
1464 }
1465 }
1466 if !ok {
1467 c.sendAlert(alertHandshakeFailure)
1468 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
1469 }
1470
1471 c.verifiedChains = chains
1472 }
1473
1474 if len(certs) > 0 {
1475 var pub crypto.PublicKey
1476 switch key := certs[0].PublicKey.(type) {
1477 case *ecdsa.PublicKey, *rsa.PublicKey:
1478 pub = key
1479 default:
1480 c.sendAlert(alertUnsupportedCertificate)
1481 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
1482 }
1483 c.peerCertificates = certs
1484 return pub, nil
1485 }
1486
1487 return nil, nil
1488}
1489
David Benjamin83c0bc92014-08-04 01:23:53 -04001490func (hs *serverHandshakeState) writeServerHash(msg []byte) {
1491 // writeServerHash is called before writeRecord.
1492 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1493}
1494
1495func (hs *serverHandshakeState) writeClientHash(msg []byte) {
1496 // writeClientHash is called after readHandshake.
1497 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1498}
1499
1500func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
1501 if hs.c.isDTLS {
1502 // This is somewhat hacky. DTLS hashes a slightly different format.
1503 // First, the TLS header.
1504 hs.finishedHash.Write(msg[:4])
1505 // Then the sequence number and reassembled fragment offset (always 0).
1506 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1507 // Then the reassembled fragment (always equal to the message length).
1508 hs.finishedHash.Write(msg[1:4])
1509 // And then the message body.
1510 hs.finishedHash.Write(msg[4:])
1511 } else {
1512 hs.finishedHash.Write(msg)
1513 }
1514}
1515
Adam Langley95c29f32014-06-20 12:00:00 -07001516// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
1517// is acceptable to use.
Nick Harper728eed82016-07-07 17:36:52 -07001518func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk, pskOk bool) *cipherSuite {
Adam Langley95c29f32014-06-20 12:00:00 -07001519 for _, supported := range supportedCipherSuites {
1520 if id == supported {
1521 var candidate *cipherSuite
1522
1523 for _, s := range cipherSuites {
1524 if s.id == id {
1525 candidate = s
1526 break
1527 }
1528 }
1529 if candidate == nil {
1530 continue
1531 }
1532 // Don't select a ciphersuite which we can't
1533 // support for this client.
David Benjamin0407e762016-06-17 16:41:18 -04001534 if !c.config.Bugs.EnableAllCiphers {
Nick Harper728eed82016-07-07 17:36:52 -07001535 if (candidate.flags&suitePSK != 0) && !pskOk {
1536 continue
1537 }
David Benjamin0407e762016-06-17 16:41:18 -04001538 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
1539 continue
1540 }
1541 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
1542 continue
1543 }
1544 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
1545 continue
1546 }
Nick Harper728eed82016-07-07 17:36:52 -07001547 if version >= VersionTLS13 && candidate.flags&suiteTLS13 == 0 {
1548 continue
1549 }
David Benjamin0407e762016-06-17 16:41:18 -04001550 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
1551 continue
1552 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001553 }
Adam Langley95c29f32014-06-20 12:00:00 -07001554 return candidate
1555 }
1556 }
1557
1558 return nil
1559}
David Benjaminf93995b2015-11-05 18:23:20 -05001560
1561func isTLS12Cipher(id uint16) bool {
1562 for _, cipher := range cipherSuites {
1563 if cipher.id != id {
1564 continue
1565 }
1566 return cipher.flags&suiteTLS12 != 0
1567 }
1568 // Unknown cipher.
1569 return false
1570}