blob: 2d9db44d15920ee04c2e6d049f8e6bfd850778dd [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 }
52 isResume, err := hs.readClientHello()
53 if err != nil {
54 return err
55 }
56
57 // For an overview of TLS handshaking, see https://tools.ietf.org/html/rfc5246#section-7.3
58 if isResume {
59 // The client has included a session ticket and so we do an abbreviated handshake.
60 if err := hs.doResumeHandshake(); err != nil {
61 return err
62 }
63 if err := hs.establishKeys(); err != nil {
64 return err
65 }
David Benjaminbed9aae2014-08-07 19:13:38 -040066 if c.config.Bugs.RenewTicketOnResume {
67 if err := hs.sendSessionTicket(); err != nil {
68 return err
69 }
70 }
Adam Langleyaf0e32c2015-06-03 09:57:23 -070071 if err := hs.sendFinished(c.firstFinished[:]); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -070072 return err
73 }
David Benjamin83f90402015-01-27 01:09:43 -050074 // Most retransmits are triggered by a timeout, but the final
75 // leg of the handshake is retransmited upon re-receiving a
76 // Finished.
David Benjaminb3774b92015-01-31 17:16:01 -050077 if err := c.simulatePacketLoss(func() {
78 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
David Benjamina4e6d482015-03-02 19:10:53 -050079 c.dtlsFlushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -050080 }); err != nil {
David Benjamin83f90402015-01-27 01:09:43 -050081 return err
82 }
Adam Langleyaf0e32c2015-06-03 09:57:23 -070083 if err := hs.readFinished(nil, isResume); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -070084 return err
85 }
86 c.didResume = true
87 } else {
88 // The client didn't include a session ticket, or it wasn't
89 // valid so we do a full handshake.
90 if err := hs.doFullHandshake(); err != nil {
91 return err
92 }
93 if err := hs.establishKeys(); err != nil {
94 return err
95 }
Adam Langleyaf0e32c2015-06-03 09:57:23 -070096 if err := hs.readFinished(c.firstFinished[:], isResume); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -070097 return err
98 }
David Benjamin1c633152015-04-02 20:19:11 -040099 if c.config.Bugs.AlertBeforeFalseStartTest != 0 {
100 c.sendAlert(c.config.Bugs.AlertBeforeFalseStartTest)
101 }
David Benjamine58c4f52014-08-24 03:47:07 -0400102 if c.config.Bugs.ExpectFalseStart {
103 if err := c.readRecord(recordTypeApplicationData); err != nil {
David Benjamin1c633152015-04-02 20:19:11 -0400104 return fmt.Errorf("tls: peer did not false start: %s", err)
David Benjamine58c4f52014-08-24 03:47:07 -0400105 }
106 }
Adam Langley95c29f32014-06-20 12:00:00 -0700107 if err := hs.sendSessionTicket(); err != nil {
108 return err
109 }
Adam Langleyaf0e32c2015-06-03 09:57:23 -0700110 if err := hs.sendFinished(nil); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700111 return err
112 }
113 }
114 c.handshakeComplete = true
David Benjaminc565ebb2015-04-03 04:06:36 -0400115 copy(c.clientRandom[:], hs.clientHello.random)
116 copy(c.serverRandom[:], hs.hello.random)
117 copy(c.masterSecret[:], hs.masterSecret)
Adam Langley95c29f32014-06-20 12:00:00 -0700118
119 return nil
120}
121
122// readClientHello reads a ClientHello message from the client and decides
123// whether we will perform session resumption.
124func (hs *serverHandshakeState) readClientHello() (isResume bool, err error) {
125 config := hs.c.config
126 c := hs.c
127
David Benjamin83f90402015-01-27 01:09:43 -0500128 if err := c.simulatePacketLoss(nil); err != nil {
129 return false, err
130 }
Adam Langley95c29f32014-06-20 12:00:00 -0700131 msg, err := c.readHandshake()
132 if err != nil {
133 return false, err
134 }
135 var ok bool
136 hs.clientHello, ok = msg.(*clientHelloMsg)
137 if !ok {
138 c.sendAlert(alertUnexpectedMessage)
139 return false, unexpectedMessageError(hs.clientHello, msg)
140 }
Adam Langley33ad2b52015-07-20 17:43:53 -0700141 if size := config.Bugs.RequireClientHelloSize; size != 0 && len(hs.clientHello.raw) != size {
142 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 -0800143 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400144
145 if c.isDTLS && !config.Bugs.SkipHelloVerifyRequest {
David Benjamin8bc38f52014-08-16 12:07:27 -0400146 // Per RFC 6347, the version field in HelloVerifyRequest SHOULD
147 // be always DTLS 1.0
David Benjamin83c0bc92014-08-04 01:23:53 -0400148 helloVerifyRequest := &helloVerifyRequestMsg{
David Benjamin8bc38f52014-08-16 12:07:27 -0400149 vers: VersionTLS10,
David Benjamin83c0bc92014-08-04 01:23:53 -0400150 cookie: make([]byte, 32),
151 }
152 if _, err := io.ReadFull(c.config.rand(), helloVerifyRequest.cookie); err != nil {
153 c.sendAlert(alertInternalError)
154 return false, errors.New("dtls: short read from Rand: " + err.Error())
155 }
156 c.writeRecord(recordTypeHandshake, helloVerifyRequest.marshal())
David Benjamina4e6d482015-03-02 19:10:53 -0500157 c.dtlsFlushHandshake()
David Benjamin83c0bc92014-08-04 01:23:53 -0400158
David Benjamin83f90402015-01-27 01:09:43 -0500159 if err := c.simulatePacketLoss(nil); err != nil {
160 return false, err
161 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400162 msg, err := c.readHandshake()
163 if err != nil {
164 return false, err
165 }
166 newClientHello, ok := msg.(*clientHelloMsg)
167 if !ok {
168 c.sendAlert(alertUnexpectedMessage)
169 return false, unexpectedMessageError(hs.clientHello, msg)
170 }
171 if !bytes.Equal(newClientHello.cookie, helloVerifyRequest.cookie) {
172 return false, errors.New("dtls: invalid cookie")
173 }
David Benjaminf2fedef2014-08-16 01:37:34 -0400174
175 // Apart from the cookie, the two ClientHellos must
176 // match. Note that clientHello.equal compares the
177 // serialization, so we make a copy.
178 oldClientHelloCopy := *hs.clientHello
179 oldClientHelloCopy.raw = nil
180 oldClientHelloCopy.cookie = nil
181 newClientHelloCopy := *newClientHello
182 newClientHelloCopy.raw = nil
183 newClientHelloCopy.cookie = nil
184 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400185 return false, errors.New("dtls: retransmitted ClientHello does not match")
186 }
187 hs.clientHello = newClientHello
188 }
189
David Benjaminc44b1df2014-11-23 12:11:01 -0500190 if config.Bugs.RequireSameRenegoClientVersion && c.clientVersion != 0 {
191 if c.clientVersion != hs.clientHello.vers {
192 return false, fmt.Errorf("tls: client offered different version on renego")
193 }
194 }
195 c.clientVersion = hs.clientHello.vers
196
David Benjamin6ae7f072015-01-26 10:22:13 -0500197 // Reject < 1.2 ClientHellos with signature_algorithms.
Nick Harper60edffd2016-06-21 15:19:24 -0700198 if c.clientVersion < VersionTLS12 && len(hs.clientHello.signatureAlgorithms) > 0 {
David Benjamin6ae7f072015-01-26 10:22:13 -0500199 return false, fmt.Errorf("tls: client included signature_algorithms before TLS 1.2")
200 }
David Benjamin72dc7832015-03-16 17:49:43 -0400201 if config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
Nick Harper60edffd2016-06-21 15:19:24 -0700202 hs.clientHello.signatureAlgorithms = config.signatureAlgorithmsForServer()
David Benjamin72dc7832015-03-16 17:49:43 -0400203 }
David Benjamin6ae7f072015-01-26 10:22:13 -0500204
David Benjaminf93995b2015-11-05 18:23:20 -0500205 // Check the client cipher list is consistent with the version.
206 if hs.clientHello.vers < VersionTLS12 {
207 for _, id := range hs.clientHello.cipherSuites {
208 if isTLS12Cipher(id) {
209 return false, fmt.Errorf("tls: client offered TLS 1.2 cipher before TLS 1.2")
210 }
211 }
212 }
213
David Benjamincecee272016-06-30 13:33:47 -0400214 c.vers, ok = config.mutualVersion(hs.clientHello.vers, c.isDTLS)
David Benjamin8bc38f52014-08-16 12:07:27 -0400215 if !ok {
216 c.sendAlert(alertProtocolVersion)
217 return false, fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
218 }
Adam Langley95c29f32014-06-20 12:00:00 -0700219 c.haveVers = true
220
David Benjamin399e7c92015-07-30 23:01:27 -0400221 hs.hello = &serverHelloMsg{
222 isDTLS: c.isDTLS,
Adam Langley09505632015-07-30 18:10:13 -0700223 customExtension: config.Bugs.CustomExtension,
David Benjamin76c2efc2015-08-31 14:24:29 -0400224 npnLast: config.Bugs.SwapNPNAndALPN,
Adam Langley09505632015-07-30 18:10:13 -0700225 }
Adam Langley95c29f32014-06-20 12:00:00 -0700226
227 supportedCurve := false
228 preferredCurves := config.curvePreferences()
David Benjaminc574f412015-04-20 11:13:01 -0400229 if config.Bugs.IgnorePeerCurvePreferences {
230 hs.clientHello.supportedCurves = preferredCurves
231 }
Adam Langley95c29f32014-06-20 12:00:00 -0700232Curves:
233 for _, curve := range hs.clientHello.supportedCurves {
234 for _, supported := range preferredCurves {
235 if supported == curve {
236 supportedCurve = true
237 break Curves
238 }
239 }
240 }
241
242 supportedPointFormat := false
243 for _, pointFormat := range hs.clientHello.supportedPoints {
244 if pointFormat == pointFormatUncompressed {
245 supportedPointFormat = true
246 break
247 }
248 }
249 hs.ellipticOk = supportedCurve && supportedPointFormat
250
251 foundCompression := false
252 // We only support null compression, so check that the client offered it.
253 for _, compression := range hs.clientHello.compressionMethods {
254 if compression == compressionNone {
255 foundCompression = true
256 break
257 }
258 }
259
260 if !foundCompression {
261 c.sendAlert(alertHandshakeFailure)
262 return false, errors.New("tls: client does not support uncompressed connections")
263 }
264
265 hs.hello.vers = c.vers
266 hs.hello.random = make([]byte, 32)
267 _, err = io.ReadFull(config.rand(), hs.hello.random)
268 if err != nil {
269 c.sendAlert(alertInternalError)
270 return false, err
271 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700272
Adam Langleycf2d4f42014-10-28 19:06:14 -0700273 if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) {
Adam Langley2ae77d22014-10-28 17:29:33 -0700274 c.sendAlert(alertHandshakeFailure)
Adam Langleycf2d4f42014-10-28 19:06:14 -0700275 return false, errors.New("tls: renegotiation mismatch")
Adam Langley2ae77d22014-10-28 17:29:33 -0700276 }
Adam Langleycf2d4f42014-10-28 19:06:14 -0700277
278 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
279 hs.hello.secureRenegotiation = append(hs.hello.secureRenegotiation, c.clientVerify...)
280 hs.hello.secureRenegotiation = append(hs.hello.secureRenegotiation, c.serverVerify...)
281 if c.config.Bugs.BadRenegotiationInfo {
282 hs.hello.secureRenegotiation[0] ^= 0x80
283 }
284 } else {
285 hs.hello.secureRenegotiation = hs.clientHello.secureRenegotiation
286 }
287
David Benjamin3e052de2015-11-25 20:10:31 -0500288 if c.noRenegotiationInfo() {
David Benjamincff0b902015-05-15 23:09:47 -0400289 hs.hello.secureRenegotiation = nil
290 }
291
Adam Langley95c29f32014-06-20 12:00:00 -0700292 hs.hello.compressionMethod = compressionNone
David Benjamin35a7a442014-07-05 00:23:20 -0400293 hs.hello.duplicateExtension = c.config.Bugs.DuplicateExtension
Adam Langley95c29f32014-06-20 12:00:00 -0700294 if len(hs.clientHello.serverName) > 0 {
295 c.serverName = hs.clientHello.serverName
296 }
David Benjaminfa055a22014-09-15 16:51:51 -0400297
298 if len(hs.clientHello.alpnProtocols) > 0 {
Adam Langleyefb0e162015-07-09 11:35:04 -0700299 if proto := c.config.Bugs.ALPNProtocol; proto != nil {
300 hs.hello.alpnProtocol = *proto
301 hs.hello.alpnProtocolEmpty = len(*proto) == 0
302 c.clientProtocol = *proto
303 c.usedALPN = true
304 } else if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
David Benjaminfa055a22014-09-15 16:51:51 -0400305 hs.hello.alpnProtocol = selectedProto
306 c.clientProtocol = selectedProto
David Benjaminfc7b0862014-09-06 13:21:53 -0400307 c.usedALPN = true
David Benjaminfa055a22014-09-15 16:51:51 -0400308 }
David Benjamin76c2efc2015-08-31 14:24:29 -0400309 }
310 if len(hs.clientHello.alpnProtocols) == 0 || c.config.Bugs.NegotiateALPNAndNPN {
David Benjaminfa055a22014-09-15 16:51:51 -0400311 // Although sending an empty NPN extension is reasonable, Firefox has
312 // had a bug around this. Best to send nothing at all if
313 // config.NextProtos is empty. See
314 // https://code.google.com/p/go/issues/detail?id=5445.
315 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
316 hs.hello.nextProtoNeg = true
317 hs.hello.nextProtos = config.NextProtos
318 }
Adam Langley95c29f32014-06-20 12:00:00 -0700319 }
Adam Langley75712922014-10-10 16:23:43 -0700320 hs.hello.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !c.config.Bugs.NoExtendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700321
322 if len(config.Certificates) == 0 {
323 c.sendAlert(alertInternalError)
324 return false, errors.New("tls: no certificates configured")
325 }
326 hs.cert = &config.Certificates[0]
327 if len(hs.clientHello.serverName) > 0 {
328 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
329 }
David Benjamine78bfde2014-09-06 12:45:15 -0400330 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
331 return false, errors.New("tls: unexpected server name")
332 }
Adam Langley95c29f32014-06-20 12:00:00 -0700333
David Benjamind30a9902014-08-24 01:44:23 -0400334 if hs.clientHello.channelIDSupported && config.RequestChannelID {
335 hs.hello.channelIDRequested = true
336 }
337
David Benjaminca6c8262014-11-15 19:06:08 -0500338 if hs.clientHello.srtpProtectionProfiles != nil {
339 SRTPLoop:
340 for _, p1 := range c.config.SRTPProtectionProfiles {
341 for _, p2 := range hs.clientHello.srtpProtectionProfiles {
342 if p1 == p2 {
343 hs.hello.srtpProtectionProfile = p1
344 c.srtpProtectionProfile = p1
345 break SRTPLoop
346 }
347 }
348 }
349 }
350
351 if c.config.Bugs.SendSRTPProtectionProfile != 0 {
352 hs.hello.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
353 }
354
Adam Langley09505632015-07-30 18:10:13 -0700355 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
356 if hs.clientHello.customExtension != *expected {
357 return false, fmt.Errorf("tls: bad custom extension contents %q", hs.clientHello.customExtension)
358 }
359 }
360
Adam Langley95c29f32014-06-20 12:00:00 -0700361 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
362
David Benjamin4b27d9f2015-05-12 22:42:52 -0400363 // For test purposes, check that the peer never offers a session when
364 // renegotiating.
365 if c.cipherSuite != nil && len(hs.clientHello.sessionId) > 0 && c.config.Bugs.FailIfResumeOnRenego {
366 return false, errors.New("tls: offered resumption on renegotiation")
367 }
368
David Benjamindd6fed92015-10-23 17:41:12 -0400369 if c.config.Bugs.FailIfSessionOffered && (len(hs.clientHello.sessionTicket) > 0 || len(hs.clientHello.sessionId) > 0) {
370 return false, errors.New("tls: client offered a session ticket or ID")
371 }
372
Adam Langley95c29f32014-06-20 12:00:00 -0700373 if hs.checkForResumption() {
374 return true, nil
375 }
376
Adam Langleyac61fa32014-06-23 12:03:11 -0700377 var scsvFound bool
378
379 for _, cipherSuite := range hs.clientHello.cipherSuites {
380 if cipherSuite == fallbackSCSV {
381 scsvFound = true
382 break
383 }
384 }
385
386 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
387 return false, errors.New("tls: no fallback SCSV found when expected")
388 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
389 return false, errors.New("tls: fallback SCSV found when not expected")
390 }
391
David Benjamin67d1fb52015-03-16 15:16:23 -0400392 if config.Bugs.IgnorePeerCipherPreferences {
393 hs.clientHello.cipherSuites = c.config.cipherSuites()
394 }
Adam Langley95c29f32014-06-20 12:00:00 -0700395 var preferenceList, supportedList []uint16
396 if c.config.PreferServerCipherSuites {
397 preferenceList = c.config.cipherSuites()
398 supportedList = hs.clientHello.cipherSuites
399 } else {
400 preferenceList = hs.clientHello.cipherSuites
401 supportedList = c.config.cipherSuites()
402 }
403
404 for _, id := range preferenceList {
405 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
406 break
407 }
408 }
409
410 if hs.suite == nil {
411 c.sendAlert(alertHandshakeFailure)
412 return false, errors.New("tls: no cipher suite supported by both client and server")
413 }
414
415 return false, nil
416}
417
418// checkForResumption returns true if we should perform resumption on this connection.
419func (hs *serverHandshakeState) checkForResumption() bool {
420 c := hs.c
421
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500422 if len(hs.clientHello.sessionTicket) > 0 {
423 if c.config.SessionTicketsDisabled {
424 return false
425 }
David Benjaminb0c8db72014-09-24 15:19:56 -0400426
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500427 var ok bool
428 if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
429 return false
430 }
431 } else {
432 if c.config.ServerSessionCache == nil {
433 return false
434 }
435
436 var ok bool
437 sessionId := string(hs.clientHello.sessionId)
438 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
439 return false
440 }
Adam Langley95c29f32014-06-20 12:00:00 -0700441 }
442
David Benjamine18d8212014-11-10 02:37:15 -0500443 // Never resume a session for a different SSL version.
444 if !c.config.Bugs.AllowSessionVersionMismatch && c.vers != hs.sessionState.vers {
445 return false
Adam Langley95c29f32014-06-20 12:00:00 -0700446 }
447
448 cipherSuiteOk := false
449 // Check that the client is still offering the ciphersuite in the session.
450 for _, id := range hs.clientHello.cipherSuites {
451 if id == hs.sessionState.cipherSuite {
452 cipherSuiteOk = true
453 break
454 }
455 }
456 if !cipherSuiteOk {
457 return false
458 }
459
460 // Check that we also support the ciphersuite from the session.
461 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk)
462 if hs.suite == nil {
463 return false
464 }
465
466 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
467 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
468 if needClientCerts && !sessionHasClientCerts {
469 return false
470 }
471 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
472 return false
473 }
474
475 return true
476}
477
478func (hs *serverHandshakeState) doResumeHandshake() error {
479 c := hs.c
480
481 hs.hello.cipherSuite = hs.suite.id
David Benjaminece3de92015-03-16 18:02:20 -0400482 if c.config.Bugs.SendCipherSuite != 0 {
483 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
484 }
Adam Langley95c29f32014-06-20 12:00:00 -0700485 // We echo the client's session ID in the ServerHello to let it know
486 // that we're doing a resumption.
487 hs.hello.sessionId = hs.clientHello.sessionId
David Benjaminbed9aae2014-08-07 19:13:38 -0400488 hs.hello.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -0700489
David Benjamin80d1b352016-05-04 19:19:06 -0400490 if c.config.Bugs.SendSCTListOnResume != nil {
491 hs.hello.sctList = c.config.Bugs.SendSCTListOnResume
492 }
493
Adam Langley95c29f32014-06-20 12:00:00 -0700494 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -0400495 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -0400496 hs.writeClientHash(hs.clientHello.marshal())
497 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700498
499 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
500
501 if len(hs.sessionState.certificates) > 0 {
502 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
503 return err
504 }
505 }
506
507 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -0700508 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700509
510 return nil
511}
512
513func (hs *serverHandshakeState) doFullHandshake() error {
514 config := hs.c.config
515 c := hs.c
516
David Benjamin48cae082014-10-27 01:06:24 -0400517 isPSK := hs.suite.flags&suitePSK != 0
518 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700519 hs.hello.ocspStapling = true
520 }
521
David Benjamin61f95272014-11-25 01:55:35 -0500522 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
523 hs.hello.sctList = hs.cert.SignedCertificateTimestampList
524 }
525
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500526 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
Adam Langley95c29f32014-06-20 12:00:00 -0700527 hs.hello.cipherSuite = hs.suite.id
David Benjamin6095de82014-12-27 01:50:38 -0500528 if config.Bugs.SendCipherSuite != 0 {
529 hs.hello.cipherSuite = config.Bugs.SendCipherSuite
530 }
Adam Langley75712922014-10-10 16:23:43 -0700531 c.extendedMasterSecret = hs.hello.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700532
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500533 // Generate a session ID if we're to save the session.
534 if !hs.hello.ticketSupported && config.ServerSessionCache != nil {
535 hs.hello.sessionId = make([]byte, 32)
536 if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
537 c.sendAlert(alertInternalError)
538 return errors.New("tls: short read from Rand: " + err.Error())
539 }
540 }
541
Adam Langley95c29f32014-06-20 12:00:00 -0700542 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400543 hs.writeClientHash(hs.clientHello.marshal())
544 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700545
546 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
547
David Benjamin48cae082014-10-27 01:06:24 -0400548 if !isPSK {
549 certMsg := new(certificateMsg)
David Benjamin8923c0b2015-06-07 11:42:34 -0400550 if !config.Bugs.EmptyCertificateList {
551 certMsg.certificates = hs.cert.Certificate
552 }
David Benjamin48cae082014-10-27 01:06:24 -0400553 if !config.Bugs.UnauthenticatedECDH {
David Benjaminbcb2d912015-02-24 23:45:43 -0500554 certMsgBytes := certMsg.marshal()
555 if config.Bugs.WrongCertificateMessageType {
556 certMsgBytes[0] += 42
557 }
558 hs.writeServerHash(certMsgBytes)
559 c.writeRecord(recordTypeHandshake, certMsgBytes)
David Benjamin48cae082014-10-27 01:06:24 -0400560 }
David Benjamin1c375dd2014-07-12 00:48:23 -0400561 }
Adam Langley95c29f32014-06-20 12:00:00 -0700562
David Benjamindcd979f2015-04-20 18:26:52 -0400563 if hs.hello.ocspStapling && !c.config.Bugs.SkipCertificateStatus {
Adam Langley95c29f32014-06-20 12:00:00 -0700564 certStatus := new(certificateStatusMsg)
565 certStatus.statusType = statusTypeOCSP
566 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -0400567 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700568 c.writeRecord(recordTypeHandshake, certStatus.marshal())
569 }
570
571 keyAgreement := hs.suite.ka(c.vers)
572 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
573 if err != nil {
574 c.sendAlert(alertHandshakeFailure)
575 return err
576 }
David Benjamin9c651c92014-07-12 13:27:45 -0400577 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -0400578 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700579 c.writeRecord(recordTypeHandshake, skx.marshal())
580 }
581
582 if config.ClientAuth >= RequestClientCert {
583 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -0400584 certReq := &certificateRequestMsg{
585 certificateTypes: config.ClientCertificateTypes,
586 }
587 if certReq.certificateTypes == nil {
588 certReq.certificateTypes = []byte{
589 byte(CertTypeRSASign),
590 byte(CertTypeECDSASign),
591 }
Adam Langley95c29f32014-06-20 12:00:00 -0700592 }
593 if c.vers >= VersionTLS12 {
Nick Harper60edffd2016-06-21 15:19:24 -0700594 certReq.hasSignatureAlgorithm = true
595 if !config.Bugs.NoSignatureAlgorithms {
596 certReq.signatureAlgorithms = config.signatureAlgorithmsForServer()
David Benjamin000800a2014-11-14 01:43:59 -0500597 }
Adam Langley95c29f32014-06-20 12:00:00 -0700598 }
599
600 // An empty list of certificateAuthorities signals to
601 // the client that it may send any certificate in response
602 // to our request. When we know the CAs we trust, then
603 // we can send them down, so that the client can choose
604 // an appropriate certificate to give to us.
605 if config.ClientCAs != nil {
606 certReq.certificateAuthorities = config.ClientCAs.Subjects()
607 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400608 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700609 c.writeRecord(recordTypeHandshake, certReq.marshal())
610 }
611
612 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400613 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700614 c.writeRecord(recordTypeHandshake, helloDone.marshal())
David Benjamina4e6d482015-03-02 19:10:53 -0500615 c.dtlsFlushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700616
617 var pub crypto.PublicKey // public key for client auth, if any
618
David Benjamin83f90402015-01-27 01:09:43 -0500619 if err := c.simulatePacketLoss(nil); err != nil {
620 return err
621 }
Adam Langley95c29f32014-06-20 12:00:00 -0700622 msg, err := c.readHandshake()
623 if err != nil {
624 return err
625 }
626
627 var ok bool
628 // If we requested a client certificate, then the client must send a
629 // certificate message, even if it's empty.
630 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -0400631 var certMsg *certificateMsg
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500632 var certificates [][]byte
633 if certMsg, ok = msg.(*certificateMsg); ok {
634 if c.vers == VersionSSL30 && len(certMsg.certificates) == 0 {
635 return errors.New("tls: empty certificate message in SSL 3.0")
636 }
637
638 hs.writeClientHash(certMsg.marshal())
639 certificates = certMsg.certificates
640 } else if c.vers != VersionSSL30 {
641 // In TLS, the Certificate message is required. In SSL
642 // 3.0, the peer skips it when sending no certificates.
Adam Langley95c29f32014-06-20 12:00:00 -0700643 c.sendAlert(alertUnexpectedMessage)
644 return unexpectedMessageError(certMsg, msg)
645 }
Adam Langley95c29f32014-06-20 12:00:00 -0700646
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500647 if len(certificates) == 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700648 // The client didn't actually send a certificate
649 switch config.ClientAuth {
650 case RequireAnyClientCert, RequireAndVerifyClientCert:
651 c.sendAlert(alertBadCertificate)
652 return errors.New("tls: client didn't provide a certificate")
653 }
654 }
655
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500656 pub, err = hs.processCertsFromClient(certificates)
Adam Langley95c29f32014-06-20 12:00:00 -0700657 if err != nil {
658 return err
659 }
660
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500661 if ok {
662 msg, err = c.readHandshake()
663 if err != nil {
664 return err
665 }
Adam Langley95c29f32014-06-20 12:00:00 -0700666 }
667 }
668
669 // Get client key exchange
670 ckx, ok := msg.(*clientKeyExchangeMsg)
671 if !ok {
672 c.sendAlert(alertUnexpectedMessage)
673 return unexpectedMessageError(ckx, msg)
674 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400675 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700676
David Benjamine098ec22014-08-27 23:13:20 -0400677 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
678 if err != nil {
679 c.sendAlert(alertHandshakeFailure)
680 return err
681 }
Adam Langley75712922014-10-10 16:23:43 -0700682 if c.extendedMasterSecret {
683 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
684 } else {
685 if c.config.Bugs.RequireExtendedMasterSecret {
686 return errors.New("tls: extended master secret required but not supported by peer")
687 }
688 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
689 }
David Benjamine098ec22014-08-27 23:13:20 -0400690
Adam Langley95c29f32014-06-20 12:00:00 -0700691 // If we received a client cert in response to our certificate request message,
692 // the client will send us a certificateVerifyMsg immediately after the
693 // clientKeyExchangeMsg. This message is a digest of all preceding
694 // handshake-layer messages that is signed using the private key corresponding
695 // to the client's certificate. This allows us to verify that the client is in
696 // possession of the private key of the certificate.
697 if len(c.peerCertificates) > 0 {
698 msg, err = c.readHandshake()
699 if err != nil {
700 return err
701 }
702 certVerify, ok := msg.(*certificateVerifyMsg)
703 if !ok {
704 c.sendAlert(alertUnexpectedMessage)
705 return unexpectedMessageError(certVerify, msg)
706 }
707
David Benjaminde620d92014-07-18 15:03:41 -0400708 // Determine the signature type.
Nick Harper60edffd2016-06-21 15:19:24 -0700709 var sigAlg signatureAlgorithm
710 if certVerify.hasSignatureAlgorithm {
711 sigAlg = certVerify.signatureAlgorithm
712 if !isSupportedSignatureAlgorithm(sigAlg, config.signatureAlgorithmsForServer()) {
713 return errors.New("tls: unsupported signature algorithm for client certificate")
David Benjamin000800a2014-11-14 01:43:59 -0500714 }
Nick Harper60edffd2016-06-21 15:19:24 -0700715 c.peerSignatureAlgorithm = sigAlg
David Benjaminde620d92014-07-18 15:03:41 -0400716 }
717
Nick Harper60edffd2016-06-21 15:19:24 -0700718 if c.vers > VersionSSL30 {
719 err = verifyMessage(c.vers, pub, sigAlg, hs.finishedHash.buffer, certVerify.signature)
720 } else {
721 // SSL 3.0's client certificate construction is
722 // incompatible with signatureAlgorithm.
723 rsaPub, ok := pub.(*rsa.PublicKey)
724 if !ok {
725 err = errors.New("unsupported key type for client certificate")
726 } else {
727 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
728 err = rsa.VerifyPKCS1v15(rsaPub, crypto.MD5SHA1, digest, certVerify.signature)
David Benjaminde620d92014-07-18 15:03:41 -0400729 }
Adam Langley95c29f32014-06-20 12:00:00 -0700730 }
731 if err != nil {
732 c.sendAlert(alertBadCertificate)
733 return errors.New("could not validate signature of connection nonces: " + err.Error())
734 }
735
David Benjamin83c0bc92014-08-04 01:23:53 -0400736 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700737 }
738
David Benjamine098ec22014-08-27 23:13:20 -0400739 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -0700740
741 return nil
742}
743
744func (hs *serverHandshakeState) establishKeys() error {
745 c := hs.c
746
747 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -0700748 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 -0700749
750 var clientCipher, serverCipher interface{}
751 var clientHash, serverHash macFunction
752
753 if hs.suite.aead == nil {
754 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
755 clientHash = hs.suite.mac(c.vers, clientMAC)
756 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
757 serverHash = hs.suite.mac(c.vers, serverMAC)
758 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -0700759 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
760 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -0700761 }
762
763 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
764 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
765
766 return nil
767}
768
Adam Langleyaf0e32c2015-06-03 09:57:23 -0700769func (hs *serverHandshakeState) readFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700770 c := hs.c
771
772 c.readRecord(recordTypeChangeCipherSpec)
773 if err := c.in.error(); err != nil {
774 return err
775 }
776
777 if hs.hello.nextProtoNeg {
778 msg, err := c.readHandshake()
779 if err != nil {
780 return err
781 }
782 nextProto, ok := msg.(*nextProtoMsg)
783 if !ok {
784 c.sendAlert(alertUnexpectedMessage)
785 return unexpectedMessageError(nextProto, msg)
786 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400787 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700788 c.clientProtocol = nextProto.proto
789 }
790
David Benjamind30a9902014-08-24 01:44:23 -0400791 if hs.hello.channelIDRequested {
792 msg, err := c.readHandshake()
793 if err != nil {
794 return err
795 }
David Benjamin24599a82016-06-30 18:56:53 -0400796 channelIDMsg, ok := msg.(*channelIDMsg)
David Benjamind30a9902014-08-24 01:44:23 -0400797 if !ok {
798 c.sendAlert(alertUnexpectedMessage)
David Benjamin24599a82016-06-30 18:56:53 -0400799 return unexpectedMessageError(channelIDMsg, msg)
David Benjamind30a9902014-08-24 01:44:23 -0400800 }
David Benjamin24599a82016-06-30 18:56:53 -0400801 x := new(big.Int).SetBytes(channelIDMsg.channelID[0:32])
802 y := new(big.Int).SetBytes(channelIDMsg.channelID[32:64])
803 r := new(big.Int).SetBytes(channelIDMsg.channelID[64:96])
804 s := new(big.Int).SetBytes(channelIDMsg.channelID[96:128])
David Benjamind30a9902014-08-24 01:44:23 -0400805 if !elliptic.P256().IsOnCurve(x, y) {
806 return errors.New("tls: invalid channel ID public key")
807 }
808 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
809 var resumeHash []byte
810 if isResume {
811 resumeHash = hs.sessionState.handshakeHash
812 }
813 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
814 return errors.New("tls: invalid channel ID signature")
815 }
816 c.channelID = channelID
817
David Benjamin24599a82016-06-30 18:56:53 -0400818 hs.writeClientHash(channelIDMsg.marshal())
David Benjamind30a9902014-08-24 01:44:23 -0400819 }
820
Adam Langley95c29f32014-06-20 12:00:00 -0700821 msg, err := c.readHandshake()
822 if err != nil {
823 return err
824 }
825 clientFinished, ok := msg.(*finishedMsg)
826 if !ok {
827 c.sendAlert(alertUnexpectedMessage)
828 return unexpectedMessageError(clientFinished, msg)
829 }
830
831 verify := hs.finishedHash.clientSum(hs.masterSecret)
832 if len(verify) != len(clientFinished.verifyData) ||
833 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
834 c.sendAlert(alertHandshakeFailure)
835 return errors.New("tls: client's Finished message is incorrect")
836 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700837 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -0700838 copy(out, clientFinished.verifyData)
Adam Langley95c29f32014-06-20 12:00:00 -0700839
David Benjamin83c0bc92014-08-04 01:23:53 -0400840 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700841 return nil
842}
843
844func (hs *serverHandshakeState) sendSessionTicket() error {
Adam Langley95c29f32014-06-20 12:00:00 -0700845 c := hs.c
Adam Langley95c29f32014-06-20 12:00:00 -0700846 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -0400847 vers: c.vers,
848 cipherSuite: hs.suite.id,
849 masterSecret: hs.masterSecret,
850 certificates: hs.certsFromClient,
851 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -0700852 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500853
854 if !hs.hello.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
855 if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
856 c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
857 }
858 return nil
859 }
860
861 m := new(newSessionTicketMsg)
862
David Benjamindd6fed92015-10-23 17:41:12 -0400863 if !c.config.Bugs.SendEmptySessionTicket {
864 var err error
865 m.ticket, err = c.encryptTicket(&state)
866 if err != nil {
867 return err
868 }
Adam Langley95c29f32014-06-20 12:00:00 -0700869 }
Adam Langley95c29f32014-06-20 12:00:00 -0700870
David Benjamin83c0bc92014-08-04 01:23:53 -0400871 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700872 c.writeRecord(recordTypeHandshake, m.marshal())
873
874 return nil
875}
876
Adam Langleyaf0e32c2015-06-03 09:57:23 -0700877func (hs *serverHandshakeState) sendFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700878 c := hs.c
879
David Benjamin86271ee2014-07-21 16:14:03 -0400880 finished := new(finishedMsg)
881 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
Adam Langleyaf0e32c2015-06-03 09:57:23 -0700882 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -0400883 if c.config.Bugs.BadFinished {
884 finished.verifyData[0]++
885 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700886 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -0500887 hs.finishedBytes = finished.marshal()
888 hs.writeServerHash(hs.finishedBytes)
889 postCCSBytes := hs.finishedBytes
David Benjamin86271ee2014-07-21 16:14:03 -0400890
891 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
892 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
893 postCCSBytes = postCCSBytes[5:]
894 }
David Benjamina4e6d482015-03-02 19:10:53 -0500895 c.dtlsFlushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -0400896
David Benjamina0e52232014-07-19 17:39:58 -0400897 if !c.config.Bugs.SkipChangeCipherSpec {
David Benjamin8411b242015-11-26 12:07:28 -0500898 ccs := []byte{1}
899 if c.config.Bugs.BadChangeCipherSpec != nil {
900 ccs = c.config.Bugs.BadChangeCipherSpec
901 }
902 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamina0e52232014-07-19 17:39:58 -0400903 }
Adam Langley95c29f32014-06-20 12:00:00 -0700904
David Benjamin4189bd92015-01-25 23:52:39 -0500905 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
906 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
907 }
David Benjamindc3da932015-03-12 15:09:02 -0400908 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
909 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
910 return errors.New("tls: simulating post-CCS alert")
911 }
David Benjamin4189bd92015-01-25 23:52:39 -0500912
David Benjaminb80168e2015-02-08 18:30:14 -0500913 if !c.config.Bugs.SkipFinished {
914 c.writeRecord(recordTypeHandshake, postCCSBytes)
David Benjamina4e6d482015-03-02 19:10:53 -0500915 c.dtlsFlushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -0500916 }
Adam Langley95c29f32014-06-20 12:00:00 -0700917
David Benjaminc565ebb2015-04-03 04:06:36 -0400918 c.cipherSuite = hs.suite
Adam Langley95c29f32014-06-20 12:00:00 -0700919
920 return nil
921}
922
923// processCertsFromClient takes a chain of client certificates either from a
924// Certificates message or from a sessionState and verifies them. It returns
925// the public key of the leaf certificate.
926func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
927 c := hs.c
928
929 hs.certsFromClient = certificates
930 certs := make([]*x509.Certificate, len(certificates))
931 var err error
932 for i, asn1Data := range certificates {
933 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
934 c.sendAlert(alertBadCertificate)
935 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
936 }
937 }
938
939 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
940 opts := x509.VerifyOptions{
941 Roots: c.config.ClientCAs,
942 CurrentTime: c.config.time(),
943 Intermediates: x509.NewCertPool(),
944 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
945 }
946
947 for _, cert := range certs[1:] {
948 opts.Intermediates.AddCert(cert)
949 }
950
951 chains, err := certs[0].Verify(opts)
952 if err != nil {
953 c.sendAlert(alertBadCertificate)
954 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
955 }
956
957 ok := false
958 for _, ku := range certs[0].ExtKeyUsage {
959 if ku == x509.ExtKeyUsageClientAuth {
960 ok = true
961 break
962 }
963 }
964 if !ok {
965 c.sendAlert(alertHandshakeFailure)
966 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
967 }
968
969 c.verifiedChains = chains
970 }
971
972 if len(certs) > 0 {
973 var pub crypto.PublicKey
974 switch key := certs[0].PublicKey.(type) {
975 case *ecdsa.PublicKey, *rsa.PublicKey:
976 pub = key
977 default:
978 c.sendAlert(alertUnsupportedCertificate)
979 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
980 }
981 c.peerCertificates = certs
982 return pub, nil
983 }
984
985 return nil, nil
986}
987
David Benjamin83c0bc92014-08-04 01:23:53 -0400988func (hs *serverHandshakeState) writeServerHash(msg []byte) {
989 // writeServerHash is called before writeRecord.
990 hs.writeHash(msg, hs.c.sendHandshakeSeq)
991}
992
993func (hs *serverHandshakeState) writeClientHash(msg []byte) {
994 // writeClientHash is called after readHandshake.
995 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
996}
997
998func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
999 if hs.c.isDTLS {
1000 // This is somewhat hacky. DTLS hashes a slightly different format.
1001 // First, the TLS header.
1002 hs.finishedHash.Write(msg[:4])
1003 // Then the sequence number and reassembled fragment offset (always 0).
1004 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1005 // Then the reassembled fragment (always equal to the message length).
1006 hs.finishedHash.Write(msg[1:4])
1007 // And then the message body.
1008 hs.finishedHash.Write(msg[4:])
1009 } else {
1010 hs.finishedHash.Write(msg)
1011 }
1012}
1013
Adam Langley95c29f32014-06-20 12:00:00 -07001014// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
1015// is acceptable to use.
1016func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
1017 for _, supported := range supportedCipherSuites {
1018 if id == supported {
1019 var candidate *cipherSuite
1020
1021 for _, s := range cipherSuites {
1022 if s.id == id {
1023 candidate = s
1024 break
1025 }
1026 }
1027 if candidate == nil {
1028 continue
1029 }
1030 // Don't select a ciphersuite which we can't
1031 // support for this client.
David Benjamin0407e762016-06-17 16:41:18 -04001032 if !c.config.Bugs.EnableAllCiphers {
1033 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
1034 continue
1035 }
1036 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
1037 continue
1038 }
1039 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
1040 continue
1041 }
1042 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
1043 continue
1044 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001045 }
Adam Langley95c29f32014-06-20 12:00:00 -07001046 return candidate
1047 }
1048 }
1049
1050 return nil
1051}
David Benjaminf93995b2015-11-05 18:23:20 -05001052
1053func isTLS12Cipher(id uint16) bool {
1054 for _, cipher := range cipherSuites {
1055 if cipher.id != id {
1056 continue
1057 }
1058 return cipher.flags&suiteTLS12 != 0
1059 }
1060 // Unknown cipher.
1061 return false
1062}