blob: d2cac98c15a8545f07867b7ae11d39e6acb72494 [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"
15 "encoding/asn1"
16 "errors"
17 "fmt"
18 "io"
David Benjamind30a9902014-08-24 01:44:23 -040019 "math/big"
Adam Langley95c29f32014-06-20 12:00:00 -070020)
21
22// serverHandshakeState contains details of a server handshake in progress.
23// It's discarded once the handshake has completed.
24type serverHandshakeState struct {
25 c *Conn
26 clientHello *clientHelloMsg
27 hello *serverHelloMsg
28 suite *cipherSuite
29 ellipticOk bool
30 ecdsaOk bool
31 sessionState *sessionState
32 finishedHash finishedHash
33 masterSecret []byte
34 certsFromClient [][]byte
35 cert *Certificate
David Benjamin83f90402015-01-27 01:09:43 -050036 finishedBytes []byte
Adam Langley95c29f32014-06-20 12:00:00 -070037}
38
39// serverHandshake performs a TLS handshake as a server.
40func (c *Conn) serverHandshake() error {
41 config := c.config
42
43 // If this is the first server handshake, we generate a random key to
44 // encrypt the tickets with.
45 config.serverInitOnce.Do(config.serverInit)
46
David Benjamin83c0bc92014-08-04 01:23:53 -040047 c.sendHandshakeSeq = 0
48 c.recvHandshakeSeq = 0
49
Adam Langley95c29f32014-06-20 12:00:00 -070050 hs := serverHandshakeState{
51 c: c,
52 }
53 isResume, err := hs.readClientHello()
54 if err != nil {
55 return err
56 }
57
58 // For an overview of TLS handshaking, see https://tools.ietf.org/html/rfc5246#section-7.3
59 if isResume {
60 // The client has included a session ticket and so we do an abbreviated handshake.
61 if err := hs.doResumeHandshake(); err != nil {
62 return err
63 }
64 if err := hs.establishKeys(); err != nil {
65 return err
66 }
David Benjaminbed9aae2014-08-07 19:13:38 -040067 if c.config.Bugs.RenewTicketOnResume {
68 if err := hs.sendSessionTicket(); err != nil {
69 return err
70 }
71 }
Adam Langleyaf0e32c2015-06-03 09:57:23 -070072 if err := hs.sendFinished(c.firstFinished[:]); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -070073 return err
74 }
David Benjamin83f90402015-01-27 01:09:43 -050075 // Most retransmits are triggered by a timeout, but the final
76 // leg of the handshake is retransmited upon re-receiving a
77 // Finished.
David Benjaminb3774b92015-01-31 17:16:01 -050078 if err := c.simulatePacketLoss(func() {
79 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
David Benjamina4e6d482015-03-02 19:10:53 -050080 c.dtlsFlushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -050081 }); err != nil {
David Benjamin83f90402015-01-27 01:09:43 -050082 return err
83 }
Adam Langleyaf0e32c2015-06-03 09:57:23 -070084 if err := hs.readFinished(nil, isResume); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -070085 return err
86 }
87 c.didResume = true
88 } else {
89 // The client didn't include a session ticket, or it wasn't
90 // valid so we do a full handshake.
91 if err := hs.doFullHandshake(); err != nil {
92 return err
93 }
94 if err := hs.establishKeys(); err != nil {
95 return err
96 }
Adam Langleyaf0e32c2015-06-03 09:57:23 -070097 if err := hs.readFinished(c.firstFinished[:], isResume); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -070098 return err
99 }
David Benjamin1c633152015-04-02 20:19:11 -0400100 if c.config.Bugs.AlertBeforeFalseStartTest != 0 {
101 c.sendAlert(c.config.Bugs.AlertBeforeFalseStartTest)
102 }
David Benjamine58c4f52014-08-24 03:47:07 -0400103 if c.config.Bugs.ExpectFalseStart {
104 if err := c.readRecord(recordTypeApplicationData); err != nil {
David Benjamin1c633152015-04-02 20:19:11 -0400105 return fmt.Errorf("tls: peer did not false start: %s", err)
David Benjamine58c4f52014-08-24 03:47:07 -0400106 }
107 }
Adam Langley95c29f32014-06-20 12:00:00 -0700108 if err := hs.sendSessionTicket(); err != nil {
109 return err
110 }
Adam Langleyaf0e32c2015-06-03 09:57:23 -0700111 if err := hs.sendFinished(nil); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700112 return err
113 }
114 }
115 c.handshakeComplete = true
David Benjaminc565ebb2015-04-03 04:06:36 -0400116 copy(c.clientRandom[:], hs.clientHello.random)
117 copy(c.serverRandom[:], hs.hello.random)
118 copy(c.masterSecret[:], hs.masterSecret)
Adam Langley95c29f32014-06-20 12:00:00 -0700119
120 return nil
121}
122
123// readClientHello reads a ClientHello message from the client and decides
124// whether we will perform session resumption.
125func (hs *serverHandshakeState) readClientHello() (isResume bool, err error) {
126 config := hs.c.config
127 c := hs.c
128
David Benjamin83f90402015-01-27 01:09:43 -0500129 if err := c.simulatePacketLoss(nil); err != nil {
130 return false, err
131 }
Adam Langley95c29f32014-06-20 12:00:00 -0700132 msg, err := c.readHandshake()
133 if err != nil {
134 return false, err
135 }
136 var ok bool
137 hs.clientHello, ok = msg.(*clientHelloMsg)
138 if !ok {
139 c.sendAlert(alertUnexpectedMessage)
140 return false, unexpectedMessageError(hs.clientHello, msg)
141 }
Adam Langley33ad2b52015-07-20 17:43:53 -0700142 if size := config.Bugs.RequireClientHelloSize; size != 0 && len(hs.clientHello.raw) != size {
143 return false, fmt.Errorf("tls: ClientHello record size is %d, but expected %d", len(hs.clientHello.raw), size)
Feng Lu41aa3252014-11-21 22:47:56 -0800144 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400145
146 if c.isDTLS && !config.Bugs.SkipHelloVerifyRequest {
David Benjamin8bc38f52014-08-16 12:07:27 -0400147 // Per RFC 6347, the version field in HelloVerifyRequest SHOULD
148 // be always DTLS 1.0
David Benjamin83c0bc92014-08-04 01:23:53 -0400149 helloVerifyRequest := &helloVerifyRequestMsg{
David Benjamin8bc38f52014-08-16 12:07:27 -0400150 vers: VersionTLS10,
David Benjamin83c0bc92014-08-04 01:23:53 -0400151 cookie: make([]byte, 32),
152 }
153 if _, err := io.ReadFull(c.config.rand(), helloVerifyRequest.cookie); err != nil {
154 c.sendAlert(alertInternalError)
155 return false, errors.New("dtls: short read from Rand: " + err.Error())
156 }
157 c.writeRecord(recordTypeHandshake, helloVerifyRequest.marshal())
David Benjamina4e6d482015-03-02 19:10:53 -0500158 c.dtlsFlushHandshake()
David Benjamin83c0bc92014-08-04 01:23:53 -0400159
David Benjamin83f90402015-01-27 01:09:43 -0500160 if err := c.simulatePacketLoss(nil); err != nil {
161 return false, err
162 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400163 msg, err := c.readHandshake()
164 if err != nil {
165 return false, err
166 }
167 newClientHello, ok := msg.(*clientHelloMsg)
168 if !ok {
169 c.sendAlert(alertUnexpectedMessage)
170 return false, unexpectedMessageError(hs.clientHello, msg)
171 }
172 if !bytes.Equal(newClientHello.cookie, helloVerifyRequest.cookie) {
173 return false, errors.New("dtls: invalid cookie")
174 }
David Benjaminf2fedef2014-08-16 01:37:34 -0400175
176 // Apart from the cookie, the two ClientHellos must
177 // match. Note that clientHello.equal compares the
178 // serialization, so we make a copy.
179 oldClientHelloCopy := *hs.clientHello
180 oldClientHelloCopy.raw = nil
181 oldClientHelloCopy.cookie = nil
182 newClientHelloCopy := *newClientHello
183 newClientHelloCopy.raw = nil
184 newClientHelloCopy.cookie = nil
185 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400186 return false, errors.New("dtls: retransmitted ClientHello does not match")
187 }
188 hs.clientHello = newClientHello
189 }
190
David Benjaminc44b1df2014-11-23 12:11:01 -0500191 if config.Bugs.RequireSameRenegoClientVersion && c.clientVersion != 0 {
192 if c.clientVersion != hs.clientHello.vers {
193 return false, fmt.Errorf("tls: client offered different version on renego")
194 }
195 }
196 c.clientVersion = hs.clientHello.vers
197
David Benjamin6ae7f072015-01-26 10:22:13 -0500198 // Reject < 1.2 ClientHellos with signature_algorithms.
199 if c.clientVersion < VersionTLS12 && len(hs.clientHello.signatureAndHashes) > 0 {
200 return false, fmt.Errorf("tls: client included signature_algorithms before TLS 1.2")
201 }
David Benjamin72dc7832015-03-16 17:49:43 -0400202 if config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
203 hs.clientHello.signatureAndHashes = config.signatureAndHashesForServer()
204 }
David Benjamin6ae7f072015-01-26 10:22:13 -0500205
David Benjaminf93995b2015-11-05 18:23:20 -0500206 // Check the client cipher list is consistent with the version.
207 if hs.clientHello.vers < VersionTLS12 {
208 for _, id := range hs.clientHello.cipherSuites {
209 if isTLS12Cipher(id) {
210 return false, fmt.Errorf("tls: client offered TLS 1.2 cipher before TLS 1.2")
211 }
212 }
213 }
214
David Benjamin8bc38f52014-08-16 12:07:27 -0400215 c.vers, ok = config.mutualVersion(hs.clientHello.vers)
216 if !ok {
217 c.sendAlert(alertProtocolVersion)
218 return false, fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
219 }
Adam Langley95c29f32014-06-20 12:00:00 -0700220 c.haveVers = true
221
David Benjamin399e7c92015-07-30 23:01:27 -0400222 hs.hello = &serverHelloMsg{
223 isDTLS: c.isDTLS,
Adam Langley09505632015-07-30 18:10:13 -0700224 customExtension: config.Bugs.CustomExtension,
David Benjamin76c2efc2015-08-31 14:24:29 -0400225 npnLast: config.Bugs.SwapNPNAndALPN,
Adam Langley09505632015-07-30 18:10:13 -0700226 }
Adam Langley95c29f32014-06-20 12:00:00 -0700227
228 supportedCurve := false
229 preferredCurves := config.curvePreferences()
David Benjaminc574f412015-04-20 11:13:01 -0400230 if config.Bugs.IgnorePeerCurvePreferences {
231 hs.clientHello.supportedCurves = preferredCurves
232 }
Adam Langley95c29f32014-06-20 12:00:00 -0700233Curves:
234 for _, curve := range hs.clientHello.supportedCurves {
235 for _, supported := range preferredCurves {
236 if supported == curve {
237 supportedCurve = true
238 break Curves
239 }
240 }
241 }
242
243 supportedPointFormat := false
244 for _, pointFormat := range hs.clientHello.supportedPoints {
245 if pointFormat == pointFormatUncompressed {
246 supportedPointFormat = true
247 break
248 }
249 }
250 hs.ellipticOk = supportedCurve && supportedPointFormat
251
252 foundCompression := false
253 // We only support null compression, so check that the client offered it.
254 for _, compression := range hs.clientHello.compressionMethods {
255 if compression == compressionNone {
256 foundCompression = true
257 break
258 }
259 }
260
261 if !foundCompression {
262 c.sendAlert(alertHandshakeFailure)
263 return false, errors.New("tls: client does not support uncompressed connections")
264 }
265
266 hs.hello.vers = c.vers
267 hs.hello.random = make([]byte, 32)
268 _, err = io.ReadFull(config.rand(), hs.hello.random)
269 if err != nil {
270 c.sendAlert(alertInternalError)
271 return false, err
272 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700273
Adam Langleycf2d4f42014-10-28 19:06:14 -0700274 if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) {
Adam Langley2ae77d22014-10-28 17:29:33 -0700275 c.sendAlert(alertHandshakeFailure)
Adam Langleycf2d4f42014-10-28 19:06:14 -0700276 return false, errors.New("tls: renegotiation mismatch")
Adam Langley2ae77d22014-10-28 17:29:33 -0700277 }
Adam Langleycf2d4f42014-10-28 19:06:14 -0700278
279 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
280 hs.hello.secureRenegotiation = append(hs.hello.secureRenegotiation, c.clientVerify...)
281 hs.hello.secureRenegotiation = append(hs.hello.secureRenegotiation, c.serverVerify...)
282 if c.config.Bugs.BadRenegotiationInfo {
283 hs.hello.secureRenegotiation[0] ^= 0x80
284 }
285 } else {
286 hs.hello.secureRenegotiation = hs.clientHello.secureRenegotiation
287 }
288
David Benjamin3e052de2015-11-25 20:10:31 -0500289 if c.noRenegotiationInfo() {
David Benjamincff0b902015-05-15 23:09:47 -0400290 hs.hello.secureRenegotiation = nil
291 }
292
Adam Langley95c29f32014-06-20 12:00:00 -0700293 hs.hello.compressionMethod = compressionNone
David Benjamin35a7a442014-07-05 00:23:20 -0400294 hs.hello.duplicateExtension = c.config.Bugs.DuplicateExtension
Adam Langley95c29f32014-06-20 12:00:00 -0700295 if len(hs.clientHello.serverName) > 0 {
296 c.serverName = hs.clientHello.serverName
297 }
David Benjaminfa055a22014-09-15 16:51:51 -0400298
299 if len(hs.clientHello.alpnProtocols) > 0 {
Adam Langleyefb0e162015-07-09 11:35:04 -0700300 if proto := c.config.Bugs.ALPNProtocol; proto != nil {
301 hs.hello.alpnProtocol = *proto
302 hs.hello.alpnProtocolEmpty = len(*proto) == 0
303 c.clientProtocol = *proto
304 c.usedALPN = true
305 } else if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
David Benjaminfa055a22014-09-15 16:51:51 -0400306 hs.hello.alpnProtocol = selectedProto
307 c.clientProtocol = selectedProto
David Benjaminfc7b0862014-09-06 13:21:53 -0400308 c.usedALPN = true
David Benjaminfa055a22014-09-15 16:51:51 -0400309 }
David Benjamin76c2efc2015-08-31 14:24:29 -0400310 }
311 if len(hs.clientHello.alpnProtocols) == 0 || c.config.Bugs.NegotiateALPNAndNPN {
David Benjaminfa055a22014-09-15 16:51:51 -0400312 // Although sending an empty NPN extension is reasonable, Firefox has
313 // had a bug around this. Best to send nothing at all if
314 // config.NextProtos is empty. See
315 // https://code.google.com/p/go/issues/detail?id=5445.
316 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
317 hs.hello.nextProtoNeg = true
318 hs.hello.nextProtos = config.NextProtos
319 }
Adam Langley95c29f32014-06-20 12:00:00 -0700320 }
Adam Langley75712922014-10-10 16:23:43 -0700321 hs.hello.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !c.config.Bugs.NoExtendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700322
323 if len(config.Certificates) == 0 {
324 c.sendAlert(alertInternalError)
325 return false, errors.New("tls: no certificates configured")
326 }
327 hs.cert = &config.Certificates[0]
328 if len(hs.clientHello.serverName) > 0 {
329 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
330 }
David Benjamine78bfde2014-09-06 12:45:15 -0400331 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
332 return false, errors.New("tls: unexpected server name")
333 }
Adam Langley95c29f32014-06-20 12:00:00 -0700334
David Benjamind30a9902014-08-24 01:44:23 -0400335 if hs.clientHello.channelIDSupported && config.RequestChannelID {
336 hs.hello.channelIDRequested = true
337 }
338
David Benjaminca6c8262014-11-15 19:06:08 -0500339 if hs.clientHello.srtpProtectionProfiles != nil {
340 SRTPLoop:
341 for _, p1 := range c.config.SRTPProtectionProfiles {
342 for _, p2 := range hs.clientHello.srtpProtectionProfiles {
343 if p1 == p2 {
344 hs.hello.srtpProtectionProfile = p1
345 c.srtpProtectionProfile = p1
346 break SRTPLoop
347 }
348 }
349 }
350 }
351
352 if c.config.Bugs.SendSRTPProtectionProfile != 0 {
353 hs.hello.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
354 }
355
Adam Langley09505632015-07-30 18:10:13 -0700356 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
357 if hs.clientHello.customExtension != *expected {
358 return false, fmt.Errorf("tls: bad custom extension contents %q", hs.clientHello.customExtension)
359 }
360 }
361
Adam Langley95c29f32014-06-20 12:00:00 -0700362 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
363
David Benjamin4b27d9f2015-05-12 22:42:52 -0400364 // For test purposes, check that the peer never offers a session when
365 // renegotiating.
366 if c.cipherSuite != nil && len(hs.clientHello.sessionId) > 0 && c.config.Bugs.FailIfResumeOnRenego {
367 return false, errors.New("tls: offered resumption on renegotiation")
368 }
369
David Benjamindd6fed92015-10-23 17:41:12 -0400370 if c.config.Bugs.FailIfSessionOffered && (len(hs.clientHello.sessionTicket) > 0 || len(hs.clientHello.sessionId) > 0) {
371 return false, errors.New("tls: client offered a session ticket or ID")
372 }
373
Adam Langley95c29f32014-06-20 12:00:00 -0700374 if hs.checkForResumption() {
375 return true, nil
376 }
377
Adam Langleyac61fa32014-06-23 12:03:11 -0700378 var scsvFound bool
379
380 for _, cipherSuite := range hs.clientHello.cipherSuites {
381 if cipherSuite == fallbackSCSV {
382 scsvFound = true
383 break
384 }
385 }
386
387 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
388 return false, errors.New("tls: no fallback SCSV found when expected")
389 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
390 return false, errors.New("tls: fallback SCSV found when not expected")
391 }
392
David Benjamin67d1fb52015-03-16 15:16:23 -0400393 if config.Bugs.IgnorePeerCipherPreferences {
394 hs.clientHello.cipherSuites = c.config.cipherSuites()
395 }
Adam Langley95c29f32014-06-20 12:00:00 -0700396 var preferenceList, supportedList []uint16
397 if c.config.PreferServerCipherSuites {
398 preferenceList = c.config.cipherSuites()
399 supportedList = hs.clientHello.cipherSuites
400 } else {
401 preferenceList = hs.clientHello.cipherSuites
402 supportedList = c.config.cipherSuites()
403 }
404
405 for _, id := range preferenceList {
406 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
407 break
408 }
409 }
410
411 if hs.suite == nil {
412 c.sendAlert(alertHandshakeFailure)
413 return false, errors.New("tls: no cipher suite supported by both client and server")
414 }
415
416 return false, nil
417}
418
419// checkForResumption returns true if we should perform resumption on this connection.
420func (hs *serverHandshakeState) checkForResumption() bool {
421 c := hs.c
422
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500423 if len(hs.clientHello.sessionTicket) > 0 {
424 if c.config.SessionTicketsDisabled {
425 return false
426 }
David Benjaminb0c8db72014-09-24 15:19:56 -0400427
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500428 var ok bool
429 if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
430 return false
431 }
432 } else {
433 if c.config.ServerSessionCache == nil {
434 return false
435 }
436
437 var ok bool
438 sessionId := string(hs.clientHello.sessionId)
439 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
440 return false
441 }
Adam Langley95c29f32014-06-20 12:00:00 -0700442 }
443
David Benjamine18d8212014-11-10 02:37:15 -0500444 // Never resume a session for a different SSL version.
445 if !c.config.Bugs.AllowSessionVersionMismatch && c.vers != hs.sessionState.vers {
446 return false
Adam Langley95c29f32014-06-20 12:00:00 -0700447 }
448
449 cipherSuiteOk := false
450 // Check that the client is still offering the ciphersuite in the session.
451 for _, id := range hs.clientHello.cipherSuites {
452 if id == hs.sessionState.cipherSuite {
453 cipherSuiteOk = true
454 break
455 }
456 }
457 if !cipherSuiteOk {
458 return false
459 }
460
461 // Check that we also support the ciphersuite from the session.
462 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk)
463 if hs.suite == nil {
464 return false
465 }
466
467 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
468 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
469 if needClientCerts && !sessionHasClientCerts {
470 return false
471 }
472 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
473 return false
474 }
475
476 return true
477}
478
479func (hs *serverHandshakeState) doResumeHandshake() error {
480 c := hs.c
481
482 hs.hello.cipherSuite = hs.suite.id
David Benjaminece3de92015-03-16 18:02:20 -0400483 if c.config.Bugs.SendCipherSuite != 0 {
484 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
485 }
Adam Langley95c29f32014-06-20 12:00:00 -0700486 // We echo the client's session ID in the ServerHello to let it know
487 // that we're doing a resumption.
488 hs.hello.sessionId = hs.clientHello.sessionId
David Benjaminbed9aae2014-08-07 19:13:38 -0400489 hs.hello.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -0700490
491 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -0400492 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -0400493 hs.writeClientHash(hs.clientHello.marshal())
494 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700495
496 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
497
498 if len(hs.sessionState.certificates) > 0 {
499 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
500 return err
501 }
502 }
503
504 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -0700505 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700506
507 return nil
508}
509
510func (hs *serverHandshakeState) doFullHandshake() error {
511 config := hs.c.config
512 c := hs.c
513
David Benjamin48cae082014-10-27 01:06:24 -0400514 isPSK := hs.suite.flags&suitePSK != 0
515 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700516 hs.hello.ocspStapling = true
517 }
518
David Benjamin61f95272014-11-25 01:55:35 -0500519 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
520 hs.hello.sctList = hs.cert.SignedCertificateTimestampList
521 }
522
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500523 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
Adam Langley95c29f32014-06-20 12:00:00 -0700524 hs.hello.cipherSuite = hs.suite.id
David Benjamin6095de82014-12-27 01:50:38 -0500525 if config.Bugs.SendCipherSuite != 0 {
526 hs.hello.cipherSuite = config.Bugs.SendCipherSuite
527 }
Adam Langley75712922014-10-10 16:23:43 -0700528 c.extendedMasterSecret = hs.hello.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700529
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500530 // Generate a session ID if we're to save the session.
531 if !hs.hello.ticketSupported && config.ServerSessionCache != nil {
532 hs.hello.sessionId = make([]byte, 32)
533 if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
534 c.sendAlert(alertInternalError)
535 return errors.New("tls: short read from Rand: " + err.Error())
536 }
537 }
538
Adam Langley95c29f32014-06-20 12:00:00 -0700539 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400540 hs.writeClientHash(hs.clientHello.marshal())
541 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700542
543 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
544
David Benjamin48cae082014-10-27 01:06:24 -0400545 if !isPSK {
546 certMsg := new(certificateMsg)
David Benjamin8923c0b2015-06-07 11:42:34 -0400547 if !config.Bugs.EmptyCertificateList {
548 certMsg.certificates = hs.cert.Certificate
549 }
David Benjamin48cae082014-10-27 01:06:24 -0400550 if !config.Bugs.UnauthenticatedECDH {
David Benjaminbcb2d912015-02-24 23:45:43 -0500551 certMsgBytes := certMsg.marshal()
552 if config.Bugs.WrongCertificateMessageType {
553 certMsgBytes[0] += 42
554 }
555 hs.writeServerHash(certMsgBytes)
556 c.writeRecord(recordTypeHandshake, certMsgBytes)
David Benjamin48cae082014-10-27 01:06:24 -0400557 }
David Benjamin1c375dd2014-07-12 00:48:23 -0400558 }
Adam Langley95c29f32014-06-20 12:00:00 -0700559
David Benjamindcd979f2015-04-20 18:26:52 -0400560 if hs.hello.ocspStapling && !c.config.Bugs.SkipCertificateStatus {
Adam Langley95c29f32014-06-20 12:00:00 -0700561 certStatus := new(certificateStatusMsg)
562 certStatus.statusType = statusTypeOCSP
563 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -0400564 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700565 c.writeRecord(recordTypeHandshake, certStatus.marshal())
566 }
567
568 keyAgreement := hs.suite.ka(c.vers)
569 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
570 if err != nil {
571 c.sendAlert(alertHandshakeFailure)
572 return err
573 }
David Benjamin9c651c92014-07-12 13:27:45 -0400574 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -0400575 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700576 c.writeRecord(recordTypeHandshake, skx.marshal())
577 }
578
579 if config.ClientAuth >= RequestClientCert {
580 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -0400581 certReq := &certificateRequestMsg{
582 certificateTypes: config.ClientCertificateTypes,
583 }
584 if certReq.certificateTypes == nil {
585 certReq.certificateTypes = []byte{
586 byte(CertTypeRSASign),
587 byte(CertTypeECDSASign),
588 }
Adam Langley95c29f32014-06-20 12:00:00 -0700589 }
590 if c.vers >= VersionTLS12 {
591 certReq.hasSignatureAndHash = true
David Benjamin000800a2014-11-14 01:43:59 -0500592 if !config.Bugs.NoSignatureAndHashes {
593 certReq.signatureAndHashes = config.signatureAndHashesForServer()
594 }
Adam Langley95c29f32014-06-20 12:00:00 -0700595 }
596
597 // An empty list of certificateAuthorities signals to
598 // the client that it may send any certificate in response
599 // to our request. When we know the CAs we trust, then
600 // we can send them down, so that the client can choose
601 // an appropriate certificate to give to us.
602 if config.ClientCAs != nil {
603 certReq.certificateAuthorities = config.ClientCAs.Subjects()
604 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400605 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700606 c.writeRecord(recordTypeHandshake, certReq.marshal())
607 }
608
609 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400610 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700611 c.writeRecord(recordTypeHandshake, helloDone.marshal())
David Benjamina4e6d482015-03-02 19:10:53 -0500612 c.dtlsFlushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700613
614 var pub crypto.PublicKey // public key for client auth, if any
615
David Benjamin83f90402015-01-27 01:09:43 -0500616 if err := c.simulatePacketLoss(nil); err != nil {
617 return err
618 }
Adam Langley95c29f32014-06-20 12:00:00 -0700619 msg, err := c.readHandshake()
620 if err != nil {
621 return err
622 }
623
624 var ok bool
625 // If we requested a client certificate, then the client must send a
626 // certificate message, even if it's empty.
627 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -0400628 var certMsg *certificateMsg
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500629 var certificates [][]byte
630 if certMsg, ok = msg.(*certificateMsg); ok {
631 if c.vers == VersionSSL30 && len(certMsg.certificates) == 0 {
632 return errors.New("tls: empty certificate message in SSL 3.0")
633 }
634
635 hs.writeClientHash(certMsg.marshal())
636 certificates = certMsg.certificates
637 } else if c.vers != VersionSSL30 {
638 // In TLS, the Certificate message is required. In SSL
639 // 3.0, the peer skips it when sending no certificates.
Adam Langley95c29f32014-06-20 12:00:00 -0700640 c.sendAlert(alertUnexpectedMessage)
641 return unexpectedMessageError(certMsg, msg)
642 }
Adam Langley95c29f32014-06-20 12:00:00 -0700643
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500644 if len(certificates) == 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700645 // The client didn't actually send a certificate
646 switch config.ClientAuth {
647 case RequireAnyClientCert, RequireAndVerifyClientCert:
648 c.sendAlert(alertBadCertificate)
649 return errors.New("tls: client didn't provide a certificate")
650 }
651 }
652
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500653 pub, err = hs.processCertsFromClient(certificates)
Adam Langley95c29f32014-06-20 12:00:00 -0700654 if err != nil {
655 return err
656 }
657
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500658 if ok {
659 msg, err = c.readHandshake()
660 if err != nil {
661 return err
662 }
Adam Langley95c29f32014-06-20 12:00:00 -0700663 }
664 }
665
666 // Get client key exchange
667 ckx, ok := msg.(*clientKeyExchangeMsg)
668 if !ok {
669 c.sendAlert(alertUnexpectedMessage)
670 return unexpectedMessageError(ckx, msg)
671 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400672 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700673
David Benjamine098ec22014-08-27 23:13:20 -0400674 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
675 if err != nil {
676 c.sendAlert(alertHandshakeFailure)
677 return err
678 }
Adam Langley75712922014-10-10 16:23:43 -0700679 if c.extendedMasterSecret {
680 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
681 } else {
682 if c.config.Bugs.RequireExtendedMasterSecret {
683 return errors.New("tls: extended master secret required but not supported by peer")
684 }
685 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
686 }
David Benjamine098ec22014-08-27 23:13:20 -0400687
Adam Langley95c29f32014-06-20 12:00:00 -0700688 // If we received a client cert in response to our certificate request message,
689 // the client will send us a certificateVerifyMsg immediately after the
690 // clientKeyExchangeMsg. This message is a digest of all preceding
691 // handshake-layer messages that is signed using the private key corresponding
692 // to the client's certificate. This allows us to verify that the client is in
693 // possession of the private key of the certificate.
694 if len(c.peerCertificates) > 0 {
695 msg, err = c.readHandshake()
696 if err != nil {
697 return err
698 }
699 certVerify, ok := msg.(*certificateVerifyMsg)
700 if !ok {
701 c.sendAlert(alertUnexpectedMessage)
702 return unexpectedMessageError(certVerify, msg)
703 }
704
David Benjaminde620d92014-07-18 15:03:41 -0400705 // Determine the signature type.
706 var signatureAndHash signatureAndHash
707 if certVerify.hasSignatureAndHash {
708 signatureAndHash = certVerify.signatureAndHash
David Benjamin000800a2014-11-14 01:43:59 -0500709 if !isSupportedSignatureAndHash(signatureAndHash, config.signatureAndHashesForServer()) {
710 return errors.New("tls: unsupported hash function for client certificate")
711 }
Steven Valdez0d62f262015-09-04 12:41:04 -0400712 c.clientCertSignatureHash = signatureAndHash.hash
David Benjaminde620d92014-07-18 15:03:41 -0400713 } else {
714 // Before TLS 1.2 the signature algorithm was implicit
715 // from the key type, and only one hash per signature
716 // algorithm was possible. Leave the hash as zero.
717 switch pub.(type) {
718 case *ecdsa.PublicKey:
719 signatureAndHash.signature = signatureECDSA
720 case *rsa.PublicKey:
721 signatureAndHash.signature = signatureRSA
722 }
723 }
724
Adam Langley95c29f32014-06-20 12:00:00 -0700725 switch key := pub.(type) {
726 case *ecdsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400727 if signatureAndHash.signature != signatureECDSA {
728 err = errors.New("tls: bad signature type for client's ECDSA certificate")
729 break
730 }
Adam Langley95c29f32014-06-20 12:00:00 -0700731 ecdsaSig := new(ecdsaSignature)
732 if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {
733 break
734 }
735 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
736 err = errors.New("ECDSA signature contained zero or negative values")
737 break
738 }
David Benjaminde620d92014-07-18 15:03:41 -0400739 var digest []byte
David Benjamine098ec22014-08-27 23:13:20 -0400740 digest, _, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400741 if err != nil {
742 break
743 }
Adam Langley95c29f32014-06-20 12:00:00 -0700744 if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {
745 err = errors.New("ECDSA verification failure")
746 break
747 }
748 case *rsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400749 if signatureAndHash.signature != signatureRSA {
750 err = errors.New("tls: bad signature type for client's RSA certificate")
751 break
752 }
753 var digest []byte
754 var hashFunc crypto.Hash
David Benjamine098ec22014-08-27 23:13:20 -0400755 digest, hashFunc, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400756 if err != nil {
757 break
758 }
Adam Langley95c29f32014-06-20 12:00:00 -0700759 err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)
760 }
761 if err != nil {
762 c.sendAlert(alertBadCertificate)
763 return errors.New("could not validate signature of connection nonces: " + err.Error())
764 }
765
David Benjamin83c0bc92014-08-04 01:23:53 -0400766 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700767 }
768
David Benjamine098ec22014-08-27 23:13:20 -0400769 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -0700770
771 return nil
772}
773
774func (hs *serverHandshakeState) establishKeys() error {
775 c := hs.c
776
777 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
778 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
779
780 var clientCipher, serverCipher interface{}
781 var clientHash, serverHash macFunction
782
783 if hs.suite.aead == nil {
784 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
785 clientHash = hs.suite.mac(c.vers, clientMAC)
786 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
787 serverHash = hs.suite.mac(c.vers, serverMAC)
788 } else {
789 clientCipher = hs.suite.aead(clientKey, clientIV)
790 serverCipher = hs.suite.aead(serverKey, serverIV)
791 }
792
793 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
794 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
795
796 return nil
797}
798
Adam Langleyaf0e32c2015-06-03 09:57:23 -0700799func (hs *serverHandshakeState) readFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700800 c := hs.c
801
802 c.readRecord(recordTypeChangeCipherSpec)
803 if err := c.in.error(); err != nil {
804 return err
805 }
806
807 if hs.hello.nextProtoNeg {
808 msg, err := c.readHandshake()
809 if err != nil {
810 return err
811 }
812 nextProto, ok := msg.(*nextProtoMsg)
813 if !ok {
814 c.sendAlert(alertUnexpectedMessage)
815 return unexpectedMessageError(nextProto, msg)
816 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400817 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700818 c.clientProtocol = nextProto.proto
819 }
820
David Benjamind30a9902014-08-24 01:44:23 -0400821 if hs.hello.channelIDRequested {
822 msg, err := c.readHandshake()
823 if err != nil {
824 return err
825 }
826 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
827 if !ok {
828 c.sendAlert(alertUnexpectedMessage)
829 return unexpectedMessageError(encryptedExtensions, msg)
830 }
831 x := new(big.Int).SetBytes(encryptedExtensions.channelID[0:32])
832 y := new(big.Int).SetBytes(encryptedExtensions.channelID[32:64])
833 r := new(big.Int).SetBytes(encryptedExtensions.channelID[64:96])
834 s := new(big.Int).SetBytes(encryptedExtensions.channelID[96:128])
835 if !elliptic.P256().IsOnCurve(x, y) {
836 return errors.New("tls: invalid channel ID public key")
837 }
838 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
839 var resumeHash []byte
840 if isResume {
841 resumeHash = hs.sessionState.handshakeHash
842 }
843 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
844 return errors.New("tls: invalid channel ID signature")
845 }
846 c.channelID = channelID
847
848 hs.writeClientHash(encryptedExtensions.marshal())
849 }
850
Adam Langley95c29f32014-06-20 12:00:00 -0700851 msg, err := c.readHandshake()
852 if err != nil {
853 return err
854 }
855 clientFinished, ok := msg.(*finishedMsg)
856 if !ok {
857 c.sendAlert(alertUnexpectedMessage)
858 return unexpectedMessageError(clientFinished, msg)
859 }
860
861 verify := hs.finishedHash.clientSum(hs.masterSecret)
862 if len(verify) != len(clientFinished.verifyData) ||
863 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
864 c.sendAlert(alertHandshakeFailure)
865 return errors.New("tls: client's Finished message is incorrect")
866 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700867 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -0700868 copy(out, clientFinished.verifyData)
Adam Langley95c29f32014-06-20 12:00:00 -0700869
David Benjamin83c0bc92014-08-04 01:23:53 -0400870 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700871 return nil
872}
873
874func (hs *serverHandshakeState) sendSessionTicket() error {
Adam Langley95c29f32014-06-20 12:00:00 -0700875 c := hs.c
Adam Langley95c29f32014-06-20 12:00:00 -0700876 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -0400877 vers: c.vers,
878 cipherSuite: hs.suite.id,
879 masterSecret: hs.masterSecret,
880 certificates: hs.certsFromClient,
881 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -0700882 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500883
884 if !hs.hello.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
885 if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
886 c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
887 }
888 return nil
889 }
890
891 m := new(newSessionTicketMsg)
892
David Benjamindd6fed92015-10-23 17:41:12 -0400893 if !c.config.Bugs.SendEmptySessionTicket {
894 var err error
895 m.ticket, err = c.encryptTicket(&state)
896 if err != nil {
897 return err
898 }
Adam Langley95c29f32014-06-20 12:00:00 -0700899 }
Adam Langley95c29f32014-06-20 12:00:00 -0700900
David Benjamin83c0bc92014-08-04 01:23:53 -0400901 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700902 c.writeRecord(recordTypeHandshake, m.marshal())
903
904 return nil
905}
906
Adam Langleyaf0e32c2015-06-03 09:57:23 -0700907func (hs *serverHandshakeState) sendFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700908 c := hs.c
909
David Benjamin86271ee2014-07-21 16:14:03 -0400910 finished := new(finishedMsg)
911 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
Adam Langleyaf0e32c2015-06-03 09:57:23 -0700912 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -0400913 if c.config.Bugs.BadFinished {
914 finished.verifyData[0]++
915 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700916 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -0500917 hs.finishedBytes = finished.marshal()
918 hs.writeServerHash(hs.finishedBytes)
919 postCCSBytes := hs.finishedBytes
David Benjamin86271ee2014-07-21 16:14:03 -0400920
921 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
922 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
923 postCCSBytes = postCCSBytes[5:]
924 }
David Benjamina4e6d482015-03-02 19:10:53 -0500925 c.dtlsFlushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -0400926
David Benjamina0e52232014-07-19 17:39:58 -0400927 if !c.config.Bugs.SkipChangeCipherSpec {
David Benjamin8411b242015-11-26 12:07:28 -0500928 ccs := []byte{1}
929 if c.config.Bugs.BadChangeCipherSpec != nil {
930 ccs = c.config.Bugs.BadChangeCipherSpec
931 }
932 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamina0e52232014-07-19 17:39:58 -0400933 }
Adam Langley95c29f32014-06-20 12:00:00 -0700934
David Benjamin4189bd92015-01-25 23:52:39 -0500935 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
936 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
937 }
David Benjamindc3da932015-03-12 15:09:02 -0400938 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
939 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
940 return errors.New("tls: simulating post-CCS alert")
941 }
David Benjamin4189bd92015-01-25 23:52:39 -0500942
David Benjaminb80168e2015-02-08 18:30:14 -0500943 if !c.config.Bugs.SkipFinished {
944 c.writeRecord(recordTypeHandshake, postCCSBytes)
David Benjamina4e6d482015-03-02 19:10:53 -0500945 c.dtlsFlushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -0500946 }
Adam Langley95c29f32014-06-20 12:00:00 -0700947
David Benjaminc565ebb2015-04-03 04:06:36 -0400948 c.cipherSuite = hs.suite
Adam Langley95c29f32014-06-20 12:00:00 -0700949
950 return nil
951}
952
953// processCertsFromClient takes a chain of client certificates either from a
954// Certificates message or from a sessionState and verifies them. It returns
955// the public key of the leaf certificate.
956func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
957 c := hs.c
958
959 hs.certsFromClient = certificates
960 certs := make([]*x509.Certificate, len(certificates))
961 var err error
962 for i, asn1Data := range certificates {
963 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
964 c.sendAlert(alertBadCertificate)
965 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
966 }
967 }
968
969 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
970 opts := x509.VerifyOptions{
971 Roots: c.config.ClientCAs,
972 CurrentTime: c.config.time(),
973 Intermediates: x509.NewCertPool(),
974 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
975 }
976
977 for _, cert := range certs[1:] {
978 opts.Intermediates.AddCert(cert)
979 }
980
981 chains, err := certs[0].Verify(opts)
982 if err != nil {
983 c.sendAlert(alertBadCertificate)
984 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
985 }
986
987 ok := false
988 for _, ku := range certs[0].ExtKeyUsage {
989 if ku == x509.ExtKeyUsageClientAuth {
990 ok = true
991 break
992 }
993 }
994 if !ok {
995 c.sendAlert(alertHandshakeFailure)
996 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
997 }
998
999 c.verifiedChains = chains
1000 }
1001
1002 if len(certs) > 0 {
1003 var pub crypto.PublicKey
1004 switch key := certs[0].PublicKey.(type) {
1005 case *ecdsa.PublicKey, *rsa.PublicKey:
1006 pub = key
1007 default:
1008 c.sendAlert(alertUnsupportedCertificate)
1009 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
1010 }
1011 c.peerCertificates = certs
1012 return pub, nil
1013 }
1014
1015 return nil, nil
1016}
1017
David Benjamin83c0bc92014-08-04 01:23:53 -04001018func (hs *serverHandshakeState) writeServerHash(msg []byte) {
1019 // writeServerHash is called before writeRecord.
1020 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1021}
1022
1023func (hs *serverHandshakeState) writeClientHash(msg []byte) {
1024 // writeClientHash is called after readHandshake.
1025 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1026}
1027
1028func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
1029 if hs.c.isDTLS {
1030 // This is somewhat hacky. DTLS hashes a slightly different format.
1031 // First, the TLS header.
1032 hs.finishedHash.Write(msg[:4])
1033 // Then the sequence number and reassembled fragment offset (always 0).
1034 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1035 // Then the reassembled fragment (always equal to the message length).
1036 hs.finishedHash.Write(msg[1:4])
1037 // And then the message body.
1038 hs.finishedHash.Write(msg[4:])
1039 } else {
1040 hs.finishedHash.Write(msg)
1041 }
1042}
1043
Adam Langley95c29f32014-06-20 12:00:00 -07001044// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
1045// is acceptable to use.
1046func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
1047 for _, supported := range supportedCipherSuites {
1048 if id == supported {
1049 var candidate *cipherSuite
1050
1051 for _, s := range cipherSuites {
1052 if s.id == id {
1053 candidate = s
1054 break
1055 }
1056 }
1057 if candidate == nil {
1058 continue
1059 }
1060 // Don't select a ciphersuite which we can't
1061 // support for this client.
1062 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
1063 continue
1064 }
1065 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
1066 continue
1067 }
David Benjamin39ebf532014-08-31 02:23:49 -04001068 if !c.config.Bugs.SkipCipherVersionCheck && version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
Adam Langley95c29f32014-06-20 12:00:00 -07001069 continue
1070 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001071 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
1072 continue
1073 }
Adam Langley95c29f32014-06-20 12:00:00 -07001074 return candidate
1075 }
1076 }
1077
1078 return nil
1079}
David Benjaminf93995b2015-11-05 18:23:20 -05001080
1081func isTLS12Cipher(id uint16) bool {
1082 for _, cipher := range cipherSuites {
1083 if cipher.id != id {
1084 continue
1085 }
1086 return cipher.flags&suiteTLS12 != 0
1087 }
1088 // Unknown cipher.
1089 return false
1090}