blob: ff8005bddcd43252260e8c6c220996ef0026a70b [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 Benjamin8d315d72016-07-18 01:03:18 +0200854 if c.vers < VersionTLS13 || config.Bugs.NegotiateNPNAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700855 if len(hs.clientHello.alpnProtocols) == 0 || c.config.Bugs.NegotiateALPNAndNPN {
856 // Although sending an empty NPN extension is reasonable, Firefox has
857 // had a bug around this. Best to send nothing at all if
858 // config.NextProtos is empty. See
859 // https://code.google.com/p/go/issues/detail?id=5445.
860 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
861 serverExtensions.nextProtoNeg = true
862 serverExtensions.nextProtos = config.NextProtos
863 serverExtensions.npnLast = config.Bugs.SwapNPNAndALPN
864 }
David Benjamin7d79f832016-07-04 09:20:45 -0700865 }
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.NegotiateEMSAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700869 serverExtensions.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !c.config.Bugs.NoExtendedMasterSecret
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.NegotiateChannelIDAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -0700873 if hs.clientHello.channelIDSupported && config.RequestChannelID {
874 serverExtensions.channelIDRequested = true
875 }
David Benjamin7d79f832016-07-04 09:20:45 -0700876 }
877
878 if hs.clientHello.srtpProtectionProfiles != nil {
879 SRTPLoop:
880 for _, p1 := range c.config.SRTPProtectionProfiles {
881 for _, p2 := range hs.clientHello.srtpProtectionProfiles {
882 if p1 == p2 {
883 serverExtensions.srtpProtectionProfile = p1
884 c.srtpProtectionProfile = p1
885 break SRTPLoop
886 }
887 }
888 }
889 }
890
891 if c.config.Bugs.SendSRTPProtectionProfile != 0 {
892 serverExtensions.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
893 }
894
895 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
896 if hs.clientHello.customExtension != *expected {
897 return fmt.Errorf("tls: bad custom extension contents %q", hs.clientHello.customExtension)
898 }
899 }
900 serverExtensions.customExtension = config.Bugs.CustomExtension
901
Steven Valdez143e8b32016-07-11 13:19:03 -0400902 if c.config.Bugs.AdvertiseTicketExtension {
903 serverExtensions.ticketSupported = true
904 }
905
David Benjamin7d79f832016-07-04 09:20:45 -0700906 return nil
907}
908
Adam Langley95c29f32014-06-20 12:00:00 -0700909// checkForResumption returns true if we should perform resumption on this connection.
910func (hs *serverHandshakeState) checkForResumption() bool {
911 c := hs.c
912
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500913 if len(hs.clientHello.sessionTicket) > 0 {
914 if c.config.SessionTicketsDisabled {
915 return false
916 }
David Benjaminb0c8db72014-09-24 15:19:56 -0400917
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500918 var ok bool
919 if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
920 return false
921 }
922 } else {
923 if c.config.ServerSessionCache == nil {
924 return false
925 }
926
927 var ok bool
928 sessionId := string(hs.clientHello.sessionId)
929 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
930 return false
931 }
Adam Langley95c29f32014-06-20 12:00:00 -0700932 }
933
David Benjamine18d8212014-11-10 02:37:15 -0500934 // Never resume a session for a different SSL version.
935 if !c.config.Bugs.AllowSessionVersionMismatch && c.vers != hs.sessionState.vers {
936 return false
Adam Langley95c29f32014-06-20 12:00:00 -0700937 }
938
939 cipherSuiteOk := false
940 // Check that the client is still offering the ciphersuite in the session.
941 for _, id := range hs.clientHello.cipherSuites {
942 if id == hs.sessionState.cipherSuite {
943 cipherSuiteOk = true
944 break
945 }
946 }
947 if !cipherSuiteOk {
948 return false
949 }
950
951 // Check that we also support the ciphersuite from the session.
Nick Harper728eed82016-07-07 17:36:52 -0700952 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 -0700953 if hs.suite == nil {
954 return false
955 }
956
957 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
958 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
959 if needClientCerts && !sessionHasClientCerts {
960 return false
961 }
962 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
963 return false
964 }
965
966 return true
967}
968
969func (hs *serverHandshakeState) doResumeHandshake() error {
970 c := hs.c
971
972 hs.hello.cipherSuite = hs.suite.id
David Benjaminece3de92015-03-16 18:02:20 -0400973 if c.config.Bugs.SendCipherSuite != 0 {
974 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
975 }
Adam Langley95c29f32014-06-20 12:00:00 -0700976 // We echo the client's session ID in the ServerHello to let it know
977 // that we're doing a resumption.
978 hs.hello.sessionId = hs.clientHello.sessionId
Nick Harperb3d51be2016-07-01 11:43:18 -0400979 hs.hello.extensions.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -0700980
David Benjamin80d1b352016-05-04 19:19:06 -0400981 if c.config.Bugs.SendSCTListOnResume != nil {
Nick Harperb3d51be2016-07-01 11:43:18 -0400982 hs.hello.extensions.sctList = c.config.Bugs.SendSCTListOnResume
David Benjamin80d1b352016-05-04 19:19:06 -0400983 }
984
Adam Langley95c29f32014-06-20 12:00:00 -0700985 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -0400986 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -0400987 hs.writeClientHash(hs.clientHello.marshal())
988 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700989
990 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
991
992 if len(hs.sessionState.certificates) > 0 {
993 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
994 return err
995 }
996 }
997
998 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -0700999 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -07001000
1001 return nil
1002}
1003
1004func (hs *serverHandshakeState) doFullHandshake() error {
1005 config := hs.c.config
1006 c := hs.c
1007
David Benjamin48cae082014-10-27 01:06:24 -04001008 isPSK := hs.suite.flags&suitePSK != 0
1009 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001010 hs.hello.extensions.ocspStapling = true
Adam Langley95c29f32014-06-20 12:00:00 -07001011 }
1012
David Benjamin61f95272014-11-25 01:55:35 -05001013 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001014 hs.hello.extensions.sctList = hs.cert.SignedCertificateTimestampList
David Benjamin61f95272014-11-25 01:55:35 -05001015 }
1016
Nick Harperb3d51be2016-07-01 11:43:18 -04001017 hs.hello.extensions.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
Adam Langley95c29f32014-06-20 12:00:00 -07001018 hs.hello.cipherSuite = hs.suite.id
David Benjamin6095de82014-12-27 01:50:38 -05001019 if config.Bugs.SendCipherSuite != 0 {
1020 hs.hello.cipherSuite = config.Bugs.SendCipherSuite
1021 }
Nick Harperb3d51be2016-07-01 11:43:18 -04001022 c.extendedMasterSecret = hs.hello.extensions.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -07001023
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001024 // Generate a session ID if we're to save the session.
Nick Harperb3d51be2016-07-01 11:43:18 -04001025 if !hs.hello.extensions.ticketSupported && config.ServerSessionCache != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001026 hs.hello.sessionId = make([]byte, 32)
1027 if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
1028 c.sendAlert(alertInternalError)
1029 return errors.New("tls: short read from Rand: " + err.Error())
1030 }
1031 }
1032
Adam Langley95c29f32014-06-20 12:00:00 -07001033 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -04001034 hs.writeClientHash(hs.clientHello.marshal())
1035 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001036
1037 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
1038
David Benjamin48cae082014-10-27 01:06:24 -04001039 if !isPSK {
1040 certMsg := new(certificateMsg)
David Benjamin8923c0b2015-06-07 11:42:34 -04001041 if !config.Bugs.EmptyCertificateList {
1042 certMsg.certificates = hs.cert.Certificate
1043 }
David Benjamin48cae082014-10-27 01:06:24 -04001044 if !config.Bugs.UnauthenticatedECDH {
David Benjaminbcb2d912015-02-24 23:45:43 -05001045 certMsgBytes := certMsg.marshal()
David Benjaminbcb2d912015-02-24 23:45:43 -05001046 hs.writeServerHash(certMsgBytes)
1047 c.writeRecord(recordTypeHandshake, certMsgBytes)
David Benjamin48cae082014-10-27 01:06:24 -04001048 }
David Benjamin1c375dd2014-07-12 00:48:23 -04001049 }
Adam Langley95c29f32014-06-20 12:00:00 -07001050
Nick Harperb3d51be2016-07-01 11:43:18 -04001051 if hs.hello.extensions.ocspStapling && !c.config.Bugs.SkipCertificateStatus {
Adam Langley95c29f32014-06-20 12:00:00 -07001052 certStatus := new(certificateStatusMsg)
1053 certStatus.statusType = statusTypeOCSP
1054 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -04001055 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001056 c.writeRecord(recordTypeHandshake, certStatus.marshal())
1057 }
1058
1059 keyAgreement := hs.suite.ka(c.vers)
1060 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
1061 if err != nil {
1062 c.sendAlert(alertHandshakeFailure)
1063 return err
1064 }
Steven Valdez5440fe02016-07-18 12:40:30 -04001065 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
1066 c.curveID = ecdhe.curveID
1067 }
David Benjamin9c651c92014-07-12 13:27:45 -04001068 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -04001069 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001070 c.writeRecord(recordTypeHandshake, skx.marshal())
1071 }
1072
1073 if config.ClientAuth >= RequestClientCert {
1074 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -04001075 certReq := &certificateRequestMsg{
1076 certificateTypes: config.ClientCertificateTypes,
1077 }
1078 if certReq.certificateTypes == nil {
1079 certReq.certificateTypes = []byte{
1080 byte(CertTypeRSASign),
1081 byte(CertTypeECDSASign),
1082 }
Adam Langley95c29f32014-06-20 12:00:00 -07001083 }
1084 if c.vers >= VersionTLS12 {
Nick Harper60edffd2016-06-21 15:19:24 -07001085 certReq.hasSignatureAlgorithm = true
1086 if !config.Bugs.NoSignatureAlgorithms {
David Benjamin7a41d372016-07-09 11:21:54 -07001087 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin000800a2014-11-14 01:43:59 -05001088 }
Adam Langley95c29f32014-06-20 12:00:00 -07001089 }
1090
1091 // An empty list of certificateAuthorities signals to
1092 // the client that it may send any certificate in response
1093 // to our request. When we know the CAs we trust, then
1094 // we can send them down, so that the client can choose
1095 // an appropriate certificate to give to us.
1096 if config.ClientCAs != nil {
1097 certReq.certificateAuthorities = config.ClientCAs.Subjects()
1098 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001099 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001100 c.writeRecord(recordTypeHandshake, certReq.marshal())
1101 }
1102
1103 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001104 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001105 c.writeRecord(recordTypeHandshake, helloDone.marshal())
David Benjamin582ba042016-07-07 12:33:25 -07001106 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001107
1108 var pub crypto.PublicKey // public key for client auth, if any
1109
David Benjamin83f90402015-01-27 01:09:43 -05001110 if err := c.simulatePacketLoss(nil); err != nil {
1111 return err
1112 }
Adam Langley95c29f32014-06-20 12:00:00 -07001113 msg, err := c.readHandshake()
1114 if err != nil {
1115 return err
1116 }
1117
1118 var ok bool
1119 // If we requested a client certificate, then the client must send a
1120 // certificate message, even if it's empty.
1121 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -04001122 var certMsg *certificateMsg
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001123 var certificates [][]byte
1124 if certMsg, ok = msg.(*certificateMsg); ok {
1125 if c.vers == VersionSSL30 && len(certMsg.certificates) == 0 {
1126 return errors.New("tls: empty certificate message in SSL 3.0")
1127 }
1128
1129 hs.writeClientHash(certMsg.marshal())
1130 certificates = certMsg.certificates
1131 } else if c.vers != VersionSSL30 {
1132 // In TLS, the Certificate message is required. In SSL
1133 // 3.0, the peer skips it when sending no certificates.
Adam Langley95c29f32014-06-20 12:00:00 -07001134 c.sendAlert(alertUnexpectedMessage)
1135 return unexpectedMessageError(certMsg, msg)
1136 }
Adam Langley95c29f32014-06-20 12:00:00 -07001137
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001138 if len(certificates) == 0 {
Adam Langley95c29f32014-06-20 12:00:00 -07001139 // The client didn't actually send a certificate
1140 switch config.ClientAuth {
1141 case RequireAnyClientCert, RequireAndVerifyClientCert:
1142 c.sendAlert(alertBadCertificate)
1143 return errors.New("tls: client didn't provide a certificate")
1144 }
1145 }
1146
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001147 pub, err = hs.processCertsFromClient(certificates)
Adam Langley95c29f32014-06-20 12:00:00 -07001148 if err != nil {
1149 return err
1150 }
1151
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001152 if ok {
1153 msg, err = c.readHandshake()
1154 if err != nil {
1155 return err
1156 }
Adam Langley95c29f32014-06-20 12:00:00 -07001157 }
1158 }
1159
1160 // Get client key exchange
1161 ckx, ok := msg.(*clientKeyExchangeMsg)
1162 if !ok {
1163 c.sendAlert(alertUnexpectedMessage)
1164 return unexpectedMessageError(ckx, msg)
1165 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001166 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001167
David Benjamine098ec22014-08-27 23:13:20 -04001168 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
1169 if err != nil {
1170 c.sendAlert(alertHandshakeFailure)
1171 return err
1172 }
Adam Langley75712922014-10-10 16:23:43 -07001173 if c.extendedMasterSecret {
1174 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1175 } else {
1176 if c.config.Bugs.RequireExtendedMasterSecret {
1177 return errors.New("tls: extended master secret required but not supported by peer")
1178 }
1179 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
1180 }
David Benjamine098ec22014-08-27 23:13:20 -04001181
Adam Langley95c29f32014-06-20 12:00:00 -07001182 // If we received a client cert in response to our certificate request message,
1183 // the client will send us a certificateVerifyMsg immediately after the
1184 // clientKeyExchangeMsg. This message is a digest of all preceding
1185 // handshake-layer messages that is signed using the private key corresponding
1186 // to the client's certificate. This allows us to verify that the client is in
1187 // possession of the private key of the certificate.
1188 if len(c.peerCertificates) > 0 {
1189 msg, err = c.readHandshake()
1190 if err != nil {
1191 return err
1192 }
1193 certVerify, ok := msg.(*certificateVerifyMsg)
1194 if !ok {
1195 c.sendAlert(alertUnexpectedMessage)
1196 return unexpectedMessageError(certVerify, msg)
1197 }
1198
David Benjaminde620d92014-07-18 15:03:41 -04001199 // Determine the signature type.
Nick Harper60edffd2016-06-21 15:19:24 -07001200 var sigAlg signatureAlgorithm
1201 if certVerify.hasSignatureAlgorithm {
1202 sigAlg = certVerify.signatureAlgorithm
Nick Harper60edffd2016-06-21 15:19:24 -07001203 c.peerSignatureAlgorithm = sigAlg
David Benjaminde620d92014-07-18 15:03:41 -04001204 }
1205
Nick Harper60edffd2016-06-21 15:19:24 -07001206 if c.vers > VersionSSL30 {
David Benjamin1fb125c2016-07-08 18:52:12 -07001207 err = verifyMessage(c.vers, pub, c.config, sigAlg, hs.finishedHash.buffer, certVerify.signature)
Nick Harper60edffd2016-06-21 15:19:24 -07001208 } else {
1209 // SSL 3.0's client certificate construction is
1210 // incompatible with signatureAlgorithm.
1211 rsaPub, ok := pub.(*rsa.PublicKey)
1212 if !ok {
1213 err = errors.New("unsupported key type for client certificate")
1214 } else {
1215 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
1216 err = rsa.VerifyPKCS1v15(rsaPub, crypto.MD5SHA1, digest, certVerify.signature)
David Benjaminde620d92014-07-18 15:03:41 -04001217 }
Adam Langley95c29f32014-06-20 12:00:00 -07001218 }
1219 if err != nil {
1220 c.sendAlert(alertBadCertificate)
1221 return errors.New("could not validate signature of connection nonces: " + err.Error())
1222 }
1223
David Benjamin83c0bc92014-08-04 01:23:53 -04001224 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001225 }
1226
David Benjamine098ec22014-08-27 23:13:20 -04001227 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001228
1229 return nil
1230}
1231
1232func (hs *serverHandshakeState) establishKeys() error {
1233 c := hs.c
1234
1235 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001236 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 -07001237
1238 var clientCipher, serverCipher interface{}
1239 var clientHash, serverHash macFunction
1240
1241 if hs.suite.aead == nil {
1242 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
1243 clientHash = hs.suite.mac(c.vers, clientMAC)
1244 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
1245 serverHash = hs.suite.mac(c.vers, serverMAC)
1246 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001247 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1248 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001249 }
1250
1251 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
1252 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
1253
1254 return nil
1255}
1256
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001257func (hs *serverHandshakeState) readFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001258 c := hs.c
1259
1260 c.readRecord(recordTypeChangeCipherSpec)
1261 if err := c.in.error(); err != nil {
1262 return err
1263 }
1264
Nick Harperb3d51be2016-07-01 11:43:18 -04001265 if hs.hello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001266 msg, err := c.readHandshake()
1267 if err != nil {
1268 return err
1269 }
1270 nextProto, ok := msg.(*nextProtoMsg)
1271 if !ok {
1272 c.sendAlert(alertUnexpectedMessage)
1273 return unexpectedMessageError(nextProto, msg)
1274 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001275 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001276 c.clientProtocol = nextProto.proto
1277 }
1278
Nick Harperb3d51be2016-07-01 11:43:18 -04001279 if hs.hello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001280 msg, err := c.readHandshake()
1281 if err != nil {
1282 return err
1283 }
David Benjamin24599a82016-06-30 18:56:53 -04001284 channelIDMsg, ok := msg.(*channelIDMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001285 if !ok {
1286 c.sendAlert(alertUnexpectedMessage)
David Benjamin24599a82016-06-30 18:56:53 -04001287 return unexpectedMessageError(channelIDMsg, msg)
David Benjamind30a9902014-08-24 01:44:23 -04001288 }
David Benjamin24599a82016-06-30 18:56:53 -04001289 x := new(big.Int).SetBytes(channelIDMsg.channelID[0:32])
1290 y := new(big.Int).SetBytes(channelIDMsg.channelID[32:64])
1291 r := new(big.Int).SetBytes(channelIDMsg.channelID[64:96])
1292 s := new(big.Int).SetBytes(channelIDMsg.channelID[96:128])
David Benjamind30a9902014-08-24 01:44:23 -04001293 if !elliptic.P256().IsOnCurve(x, y) {
1294 return errors.New("tls: invalid channel ID public key")
1295 }
1296 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
1297 var resumeHash []byte
1298 if isResume {
1299 resumeHash = hs.sessionState.handshakeHash
1300 }
1301 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
1302 return errors.New("tls: invalid channel ID signature")
1303 }
1304 c.channelID = channelID
1305
David Benjamin24599a82016-06-30 18:56:53 -04001306 hs.writeClientHash(channelIDMsg.marshal())
David Benjamind30a9902014-08-24 01:44:23 -04001307 }
1308
Adam Langley95c29f32014-06-20 12:00:00 -07001309 msg, err := c.readHandshake()
1310 if err != nil {
1311 return err
1312 }
1313 clientFinished, ok := msg.(*finishedMsg)
1314 if !ok {
1315 c.sendAlert(alertUnexpectedMessage)
1316 return unexpectedMessageError(clientFinished, msg)
1317 }
1318
1319 verify := hs.finishedHash.clientSum(hs.masterSecret)
1320 if len(verify) != len(clientFinished.verifyData) ||
1321 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
1322 c.sendAlert(alertHandshakeFailure)
1323 return errors.New("tls: client's Finished message is incorrect")
1324 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001325 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001326 copy(out, clientFinished.verifyData)
Adam Langley95c29f32014-06-20 12:00:00 -07001327
David Benjamin83c0bc92014-08-04 01:23:53 -04001328 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001329 return nil
1330}
1331
1332func (hs *serverHandshakeState) sendSessionTicket() error {
Adam Langley95c29f32014-06-20 12:00:00 -07001333 c := hs.c
Adam Langley95c29f32014-06-20 12:00:00 -07001334 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -04001335 vers: c.vers,
1336 cipherSuite: hs.suite.id,
1337 masterSecret: hs.masterSecret,
1338 certificates: hs.certsFromClient,
1339 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -07001340 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001341
Nick Harperb3d51be2016-07-01 11:43:18 -04001342 if !hs.hello.extensions.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001343 if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
1344 c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
1345 }
1346 return nil
1347 }
1348
1349 m := new(newSessionTicketMsg)
1350
David Benjamindd6fed92015-10-23 17:41:12 -04001351 if !c.config.Bugs.SendEmptySessionTicket {
1352 var err error
1353 m.ticket, err = c.encryptTicket(&state)
1354 if err != nil {
1355 return err
1356 }
Adam Langley95c29f32014-06-20 12:00:00 -07001357 }
Adam Langley95c29f32014-06-20 12:00:00 -07001358
David Benjamin83c0bc92014-08-04 01:23:53 -04001359 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001360 c.writeRecord(recordTypeHandshake, m.marshal())
1361
1362 return nil
1363}
1364
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001365func (hs *serverHandshakeState) sendFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001366 c := hs.c
1367
David Benjamin86271ee2014-07-21 16:14:03 -04001368 finished := new(finishedMsg)
1369 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001370 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001371 if c.config.Bugs.BadFinished {
1372 finished.verifyData[0]++
1373 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001374 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001375 hs.finishedBytes = finished.marshal()
1376 hs.writeServerHash(hs.finishedBytes)
1377 postCCSBytes := hs.finishedBytes
David Benjamin86271ee2014-07-21 16:14:03 -04001378
1379 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
1380 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
1381 postCCSBytes = postCCSBytes[5:]
David Benjamin61672812016-07-14 23:10:43 -04001382 } else if c.config.Bugs.SendUnencryptedFinished {
1383 c.writeRecord(recordTypeHandshake, postCCSBytes)
1384 postCCSBytes = nil
David Benjamin86271ee2014-07-21 16:14:03 -04001385 }
David Benjamin582ba042016-07-07 12:33:25 -07001386 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001387
David Benjamina0e52232014-07-19 17:39:58 -04001388 if !c.config.Bugs.SkipChangeCipherSpec {
David Benjamin8411b242015-11-26 12:07:28 -05001389 ccs := []byte{1}
1390 if c.config.Bugs.BadChangeCipherSpec != nil {
1391 ccs = c.config.Bugs.BadChangeCipherSpec
1392 }
1393 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamina0e52232014-07-19 17:39:58 -04001394 }
Adam Langley95c29f32014-06-20 12:00:00 -07001395
David Benjamin4189bd92015-01-25 23:52:39 -05001396 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1397 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1398 }
David Benjamindc3da932015-03-12 15:09:02 -04001399 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1400 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1401 return errors.New("tls: simulating post-CCS alert")
1402 }
David Benjamin4189bd92015-01-25 23:52:39 -05001403
David Benjamin61672812016-07-14 23:10:43 -04001404 if !c.config.Bugs.SkipFinished && len(postCCSBytes) > 0 {
David Benjaminb80168e2015-02-08 18:30:14 -05001405 c.writeRecord(recordTypeHandshake, postCCSBytes)
David Benjamin02edcd02016-07-27 17:40:37 -04001406 if c.config.Bugs.SendExtraFinished {
1407 c.writeRecord(recordTypeHandshake, finished.marshal())
1408 }
1409
David Benjamin12d2c482016-07-24 10:56:51 -04001410 if !c.config.Bugs.PackHelloRequestWithFinished {
1411 // Defer flushing until renegotiation.
1412 c.flushHandshake()
1413 }
David Benjaminb3774b92015-01-31 17:16:01 -05001414 }
Adam Langley95c29f32014-06-20 12:00:00 -07001415
David Benjaminc565ebb2015-04-03 04:06:36 -04001416 c.cipherSuite = hs.suite
Adam Langley95c29f32014-06-20 12:00:00 -07001417
1418 return nil
1419}
1420
1421// processCertsFromClient takes a chain of client certificates either from a
1422// Certificates message or from a sessionState and verifies them. It returns
1423// the public key of the leaf certificate.
1424func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
1425 c := hs.c
1426
1427 hs.certsFromClient = certificates
1428 certs := make([]*x509.Certificate, len(certificates))
1429 var err error
1430 for i, asn1Data := range certificates {
1431 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
1432 c.sendAlert(alertBadCertificate)
1433 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
1434 }
1435 }
1436
1437 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
1438 opts := x509.VerifyOptions{
1439 Roots: c.config.ClientCAs,
1440 CurrentTime: c.config.time(),
1441 Intermediates: x509.NewCertPool(),
1442 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
1443 }
1444
1445 for _, cert := range certs[1:] {
1446 opts.Intermediates.AddCert(cert)
1447 }
1448
1449 chains, err := certs[0].Verify(opts)
1450 if err != nil {
1451 c.sendAlert(alertBadCertificate)
1452 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
1453 }
1454
1455 ok := false
1456 for _, ku := range certs[0].ExtKeyUsage {
1457 if ku == x509.ExtKeyUsageClientAuth {
1458 ok = true
1459 break
1460 }
1461 }
1462 if !ok {
1463 c.sendAlert(alertHandshakeFailure)
1464 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
1465 }
1466
1467 c.verifiedChains = chains
1468 }
1469
1470 if len(certs) > 0 {
1471 var pub crypto.PublicKey
1472 switch key := certs[0].PublicKey.(type) {
1473 case *ecdsa.PublicKey, *rsa.PublicKey:
1474 pub = key
1475 default:
1476 c.sendAlert(alertUnsupportedCertificate)
1477 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
1478 }
1479 c.peerCertificates = certs
1480 return pub, nil
1481 }
1482
1483 return nil, nil
1484}
1485
David Benjamin83c0bc92014-08-04 01:23:53 -04001486func (hs *serverHandshakeState) writeServerHash(msg []byte) {
1487 // writeServerHash is called before writeRecord.
1488 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1489}
1490
1491func (hs *serverHandshakeState) writeClientHash(msg []byte) {
1492 // writeClientHash is called after readHandshake.
1493 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1494}
1495
1496func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
1497 if hs.c.isDTLS {
1498 // This is somewhat hacky. DTLS hashes a slightly different format.
1499 // First, the TLS header.
1500 hs.finishedHash.Write(msg[:4])
1501 // Then the sequence number and reassembled fragment offset (always 0).
1502 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1503 // Then the reassembled fragment (always equal to the message length).
1504 hs.finishedHash.Write(msg[1:4])
1505 // And then the message body.
1506 hs.finishedHash.Write(msg[4:])
1507 } else {
1508 hs.finishedHash.Write(msg)
1509 }
1510}
1511
Adam Langley95c29f32014-06-20 12:00:00 -07001512// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
1513// is acceptable to use.
Nick Harper728eed82016-07-07 17:36:52 -07001514func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk, pskOk bool) *cipherSuite {
Adam Langley95c29f32014-06-20 12:00:00 -07001515 for _, supported := range supportedCipherSuites {
1516 if id == supported {
1517 var candidate *cipherSuite
1518
1519 for _, s := range cipherSuites {
1520 if s.id == id {
1521 candidate = s
1522 break
1523 }
1524 }
1525 if candidate == nil {
1526 continue
1527 }
1528 // Don't select a ciphersuite which we can't
1529 // support for this client.
David Benjamin0407e762016-06-17 16:41:18 -04001530 if !c.config.Bugs.EnableAllCiphers {
Nick Harper728eed82016-07-07 17:36:52 -07001531 if (candidate.flags&suitePSK != 0) && !pskOk {
1532 continue
1533 }
David Benjamin0407e762016-06-17 16:41:18 -04001534 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
1535 continue
1536 }
1537 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
1538 continue
1539 }
1540 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
1541 continue
1542 }
Nick Harper728eed82016-07-07 17:36:52 -07001543 if version >= VersionTLS13 && candidate.flags&suiteTLS13 == 0 {
1544 continue
1545 }
David Benjamin0407e762016-06-17 16:41:18 -04001546 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
1547 continue
1548 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001549 }
Adam Langley95c29f32014-06-20 12:00:00 -07001550 return candidate
1551 }
1552 }
1553
1554 return nil
1555}
David Benjaminf93995b2015-11-05 18:23:20 -05001556
1557func isTLS12Cipher(id uint16) bool {
1558 for _, cipher := range cipherSuites {
1559 if cipher.id != id {
1560 continue
1561 }
1562 return cipher.flags&suiteTLS12 != 0
1563 }
1564 // Unknown cipher.
1565 return false
1566}