blob: e456891d4c8dd67e74bcc6e4a13bd086dcafa46b [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
5package main
6
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
36}
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 Langley95c29f32014-06-20 12:00:00 -070071 if err := hs.sendFinished(); err != nil {
72 return err
73 }
David Benjamind30a9902014-08-24 01:44:23 -040074 if err := hs.readFinished(isResume); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -070075 return err
76 }
77 c.didResume = true
78 } else {
79 // The client didn't include a session ticket, or it wasn't
80 // valid so we do a full handshake.
81 if err := hs.doFullHandshake(); err != nil {
82 return err
83 }
84 if err := hs.establishKeys(); err != nil {
85 return err
86 }
David Benjamind30a9902014-08-24 01:44:23 -040087 if err := hs.readFinished(isResume); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -070088 return err
89 }
David Benjamine58c4f52014-08-24 03:47:07 -040090 if c.config.Bugs.ExpectFalseStart {
91 if err := c.readRecord(recordTypeApplicationData); err != nil {
92 return err
93 }
94 }
Adam Langley95c29f32014-06-20 12:00:00 -070095 if err := hs.sendSessionTicket(); err != nil {
96 return err
97 }
98 if err := hs.sendFinished(); err != nil {
99 return err
100 }
101 }
102 c.handshakeComplete = true
103
104 return nil
105}
106
107// readClientHello reads a ClientHello message from the client and decides
108// whether we will perform session resumption.
109func (hs *serverHandshakeState) readClientHello() (isResume bool, err error) {
110 config := hs.c.config
111 c := hs.c
112
113 msg, err := c.readHandshake()
114 if err != nil {
115 return false, err
116 }
117 var ok bool
118 hs.clientHello, ok = msg.(*clientHelloMsg)
119 if !ok {
120 c.sendAlert(alertUnexpectedMessage)
121 return false, unexpectedMessageError(hs.clientHello, msg)
122 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400123
124 if c.isDTLS && !config.Bugs.SkipHelloVerifyRequest {
David Benjamin8bc38f52014-08-16 12:07:27 -0400125 // Per RFC 6347, the version field in HelloVerifyRequest SHOULD
126 // be always DTLS 1.0
David Benjamin83c0bc92014-08-04 01:23:53 -0400127 helloVerifyRequest := &helloVerifyRequestMsg{
David Benjamin8bc38f52014-08-16 12:07:27 -0400128 vers: VersionTLS10,
David Benjamin83c0bc92014-08-04 01:23:53 -0400129 cookie: make([]byte, 32),
130 }
131 if _, err := io.ReadFull(c.config.rand(), helloVerifyRequest.cookie); err != nil {
132 c.sendAlert(alertInternalError)
133 return false, errors.New("dtls: short read from Rand: " + err.Error())
134 }
135 c.writeRecord(recordTypeHandshake, helloVerifyRequest.marshal())
136
137 msg, err := c.readHandshake()
138 if err != nil {
139 return false, err
140 }
141 newClientHello, ok := msg.(*clientHelloMsg)
142 if !ok {
143 c.sendAlert(alertUnexpectedMessage)
144 return false, unexpectedMessageError(hs.clientHello, msg)
145 }
146 if !bytes.Equal(newClientHello.cookie, helloVerifyRequest.cookie) {
147 return false, errors.New("dtls: invalid cookie")
148 }
David Benjaminf2fedef2014-08-16 01:37:34 -0400149
150 // Apart from the cookie, the two ClientHellos must
151 // match. Note that clientHello.equal compares the
152 // serialization, so we make a copy.
153 oldClientHelloCopy := *hs.clientHello
154 oldClientHelloCopy.raw = nil
155 oldClientHelloCopy.cookie = nil
156 newClientHelloCopy := *newClientHello
157 newClientHelloCopy.raw = nil
158 newClientHelloCopy.cookie = nil
159 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400160 return false, errors.New("dtls: retransmitted ClientHello does not match")
161 }
162 hs.clientHello = newClientHello
163 }
164
David Benjamin8bc38f52014-08-16 12:07:27 -0400165 c.vers, ok = config.mutualVersion(hs.clientHello.vers)
166 if !ok {
167 c.sendAlert(alertProtocolVersion)
168 return false, fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
169 }
Adam Langley95c29f32014-06-20 12:00:00 -0700170 c.haveVers = true
171
172 hs.hello = new(serverHelloMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400173 hs.hello.isDTLS = c.isDTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700174
175 supportedCurve := false
176 preferredCurves := config.curvePreferences()
177Curves:
178 for _, curve := range hs.clientHello.supportedCurves {
179 for _, supported := range preferredCurves {
180 if supported == curve {
181 supportedCurve = true
182 break Curves
183 }
184 }
185 }
186
187 supportedPointFormat := false
188 for _, pointFormat := range hs.clientHello.supportedPoints {
189 if pointFormat == pointFormatUncompressed {
190 supportedPointFormat = true
191 break
192 }
193 }
194 hs.ellipticOk = supportedCurve && supportedPointFormat
195
196 foundCompression := false
197 // We only support null compression, so check that the client offered it.
198 for _, compression := range hs.clientHello.compressionMethods {
199 if compression == compressionNone {
200 foundCompression = true
201 break
202 }
203 }
204
205 if !foundCompression {
206 c.sendAlert(alertHandshakeFailure)
207 return false, errors.New("tls: client does not support uncompressed connections")
208 }
209
210 hs.hello.vers = c.vers
211 hs.hello.random = make([]byte, 32)
212 _, err = io.ReadFull(config.rand(), hs.hello.random)
213 if err != nil {
214 c.sendAlert(alertInternalError)
215 return false, err
216 }
217 hs.hello.secureRenegotiation = hs.clientHello.secureRenegotiation
218 hs.hello.compressionMethod = compressionNone
David Benjamin35a7a442014-07-05 00:23:20 -0400219 hs.hello.duplicateExtension = c.config.Bugs.DuplicateExtension
Adam Langley95c29f32014-06-20 12:00:00 -0700220 if len(hs.clientHello.serverName) > 0 {
221 c.serverName = hs.clientHello.serverName
222 }
223 // Although sending an empty NPN extension is reasonable, Firefox has
224 // had a bug around this. Best to send nothing at all if
225 // config.NextProtos is empty. See
226 // https://code.google.com/p/go/issues/detail?id=5445.
227 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
228 hs.hello.nextProtoNeg = true
229 hs.hello.nextProtos = config.NextProtos
230 }
231
232 if len(config.Certificates) == 0 {
233 c.sendAlert(alertInternalError)
234 return false, errors.New("tls: no certificates configured")
235 }
236 hs.cert = &config.Certificates[0]
237 if len(hs.clientHello.serverName) > 0 {
238 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
239 }
David Benjamine78bfde2014-09-06 12:45:15 -0400240 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
241 return false, errors.New("tls: unexpected server name")
242 }
Adam Langley95c29f32014-06-20 12:00:00 -0700243
David Benjamind30a9902014-08-24 01:44:23 -0400244 if hs.clientHello.channelIDSupported && config.RequestChannelID {
245 hs.hello.channelIDRequested = true
246 }
247
Adam Langley95c29f32014-06-20 12:00:00 -0700248 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
249
250 if hs.checkForResumption() {
251 return true, nil
252 }
253
Adam Langleyac61fa32014-06-23 12:03:11 -0700254 var scsvFound bool
255
256 for _, cipherSuite := range hs.clientHello.cipherSuites {
257 if cipherSuite == fallbackSCSV {
258 scsvFound = true
259 break
260 }
261 }
262
263 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
264 return false, errors.New("tls: no fallback SCSV found when expected")
265 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
266 return false, errors.New("tls: fallback SCSV found when not expected")
267 }
268
Adam Langley95c29f32014-06-20 12:00:00 -0700269 var preferenceList, supportedList []uint16
270 if c.config.PreferServerCipherSuites {
271 preferenceList = c.config.cipherSuites()
272 supportedList = hs.clientHello.cipherSuites
273 } else {
274 preferenceList = hs.clientHello.cipherSuites
275 supportedList = c.config.cipherSuites()
276 }
277
278 for _, id := range preferenceList {
279 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
280 break
281 }
282 }
283
284 if hs.suite == nil {
285 c.sendAlert(alertHandshakeFailure)
286 return false, errors.New("tls: no cipher suite supported by both client and server")
287 }
288
289 return false, nil
290}
291
292// checkForResumption returns true if we should perform resumption on this connection.
293func (hs *serverHandshakeState) checkForResumption() bool {
294 c := hs.c
295
296 var ok bool
297 if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
298 return false
299 }
300
301 if hs.sessionState.vers > hs.clientHello.vers {
302 return false
303 }
304 if vers, ok := c.config.mutualVersion(hs.sessionState.vers); !ok || vers != hs.sessionState.vers {
305 return false
306 }
307
308 cipherSuiteOk := false
309 // Check that the client is still offering the ciphersuite in the session.
310 for _, id := range hs.clientHello.cipherSuites {
311 if id == hs.sessionState.cipherSuite {
312 cipherSuiteOk = true
313 break
314 }
315 }
316 if !cipherSuiteOk {
317 return false
318 }
319
320 // Check that we also support the ciphersuite from the session.
321 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk)
322 if hs.suite == nil {
323 return false
324 }
325
326 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
327 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
328 if needClientCerts && !sessionHasClientCerts {
329 return false
330 }
331 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
332 return false
333 }
334
335 return true
336}
337
338func (hs *serverHandshakeState) doResumeHandshake() error {
339 c := hs.c
340
341 hs.hello.cipherSuite = hs.suite.id
342 // We echo the client's session ID in the ServerHello to let it know
343 // that we're doing a resumption.
344 hs.hello.sessionId = hs.clientHello.sessionId
David Benjaminbed9aae2014-08-07 19:13:38 -0400345 hs.hello.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -0700346
347 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -0400348 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -0400349 hs.writeClientHash(hs.clientHello.marshal())
350 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700351
352 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
353
354 if len(hs.sessionState.certificates) > 0 {
355 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
356 return err
357 }
358 }
359
360 hs.masterSecret = hs.sessionState.masterSecret
361
362 return nil
363}
364
365func (hs *serverHandshakeState) doFullHandshake() error {
366 config := hs.c.config
367 c := hs.c
368
369 if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
370 hs.hello.ocspStapling = true
371 }
372
373 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled
374 hs.hello.cipherSuite = hs.suite.id
375
376 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400377 hs.writeClientHash(hs.clientHello.marshal())
378 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700379
380 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
381
382 certMsg := new(certificateMsg)
383 certMsg.certificates = hs.cert.Certificate
David Benjamin1c375dd2014-07-12 00:48:23 -0400384 if !config.Bugs.UnauthenticatedECDH {
David Benjamin83c0bc92014-08-04 01:23:53 -0400385 hs.writeServerHash(certMsg.marshal())
David Benjamin1c375dd2014-07-12 00:48:23 -0400386 c.writeRecord(recordTypeHandshake, certMsg.marshal())
387 }
Adam Langley95c29f32014-06-20 12:00:00 -0700388
389 if hs.hello.ocspStapling {
390 certStatus := new(certificateStatusMsg)
391 certStatus.statusType = statusTypeOCSP
392 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -0400393 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700394 c.writeRecord(recordTypeHandshake, certStatus.marshal())
395 }
396
397 keyAgreement := hs.suite.ka(c.vers)
398 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
399 if err != nil {
400 c.sendAlert(alertHandshakeFailure)
401 return err
402 }
David Benjamin9c651c92014-07-12 13:27:45 -0400403 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -0400404 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700405 c.writeRecord(recordTypeHandshake, skx.marshal())
406 }
407
408 if config.ClientAuth >= RequestClientCert {
409 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -0400410 certReq := &certificateRequestMsg{
411 certificateTypes: config.ClientCertificateTypes,
412 }
413 if certReq.certificateTypes == nil {
414 certReq.certificateTypes = []byte{
415 byte(CertTypeRSASign),
416 byte(CertTypeECDSASign),
417 }
Adam Langley95c29f32014-06-20 12:00:00 -0700418 }
419 if c.vers >= VersionTLS12 {
420 certReq.hasSignatureAndHash = true
421 certReq.signatureAndHashes = supportedClientCertSignatureAlgorithms
422 }
423
424 // An empty list of certificateAuthorities signals to
425 // the client that it may send any certificate in response
426 // to our request. When we know the CAs we trust, then
427 // we can send them down, so that the client can choose
428 // an appropriate certificate to give to us.
429 if config.ClientCAs != nil {
430 certReq.certificateAuthorities = config.ClientCAs.Subjects()
431 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400432 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700433 c.writeRecord(recordTypeHandshake, certReq.marshal())
434 }
435
436 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400437 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700438 c.writeRecord(recordTypeHandshake, helloDone.marshal())
439
440 var pub crypto.PublicKey // public key for client auth, if any
441
442 msg, err := c.readHandshake()
443 if err != nil {
444 return err
445 }
446
447 var ok bool
448 // If we requested a client certificate, then the client must send a
449 // certificate message, even if it's empty.
450 if config.ClientAuth >= RequestClientCert {
451 if certMsg, ok = msg.(*certificateMsg); !ok {
452 c.sendAlert(alertUnexpectedMessage)
453 return unexpectedMessageError(certMsg, msg)
454 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400455 hs.writeClientHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700456
457 if len(certMsg.certificates) == 0 {
458 // The client didn't actually send a certificate
459 switch config.ClientAuth {
460 case RequireAnyClientCert, RequireAndVerifyClientCert:
461 c.sendAlert(alertBadCertificate)
462 return errors.New("tls: client didn't provide a certificate")
463 }
464 }
465
466 pub, err = hs.processCertsFromClient(certMsg.certificates)
467 if err != nil {
468 return err
469 }
470
471 msg, err = c.readHandshake()
472 if err != nil {
473 return err
474 }
475 }
476
477 // Get client key exchange
478 ckx, ok := msg.(*clientKeyExchangeMsg)
479 if !ok {
480 c.sendAlert(alertUnexpectedMessage)
481 return unexpectedMessageError(ckx, msg)
482 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400483 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700484
David Benjamine098ec22014-08-27 23:13:20 -0400485 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
486 if err != nil {
487 c.sendAlert(alertHandshakeFailure)
488 return err
489 }
490 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
491
Adam Langley95c29f32014-06-20 12:00:00 -0700492 // If we received a client cert in response to our certificate request message,
493 // the client will send us a certificateVerifyMsg immediately after the
494 // clientKeyExchangeMsg. This message is a digest of all preceding
495 // handshake-layer messages that is signed using the private key corresponding
496 // to the client's certificate. This allows us to verify that the client is in
497 // possession of the private key of the certificate.
498 if len(c.peerCertificates) > 0 {
499 msg, err = c.readHandshake()
500 if err != nil {
501 return err
502 }
503 certVerify, ok := msg.(*certificateVerifyMsg)
504 if !ok {
505 c.sendAlert(alertUnexpectedMessage)
506 return unexpectedMessageError(certVerify, msg)
507 }
508
David Benjaminde620d92014-07-18 15:03:41 -0400509 // Determine the signature type.
510 var signatureAndHash signatureAndHash
511 if certVerify.hasSignatureAndHash {
512 signatureAndHash = certVerify.signatureAndHash
513 } else {
514 // Before TLS 1.2 the signature algorithm was implicit
515 // from the key type, and only one hash per signature
516 // algorithm was possible. Leave the hash as zero.
517 switch pub.(type) {
518 case *ecdsa.PublicKey:
519 signatureAndHash.signature = signatureECDSA
520 case *rsa.PublicKey:
521 signatureAndHash.signature = signatureRSA
522 }
523 }
524
Adam Langley95c29f32014-06-20 12:00:00 -0700525 switch key := pub.(type) {
526 case *ecdsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400527 if signatureAndHash.signature != signatureECDSA {
528 err = errors.New("tls: bad signature type for client's ECDSA certificate")
529 break
530 }
Adam Langley95c29f32014-06-20 12:00:00 -0700531 ecdsaSig := new(ecdsaSignature)
532 if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {
533 break
534 }
535 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
536 err = errors.New("ECDSA signature contained zero or negative values")
537 break
538 }
David Benjaminde620d92014-07-18 15:03:41 -0400539 var digest []byte
David Benjamine098ec22014-08-27 23:13:20 -0400540 digest, _, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400541 if err != nil {
542 break
543 }
Adam Langley95c29f32014-06-20 12:00:00 -0700544 if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {
545 err = errors.New("ECDSA verification failure")
546 break
547 }
548 case *rsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400549 if signatureAndHash.signature != signatureRSA {
550 err = errors.New("tls: bad signature type for client's RSA certificate")
551 break
552 }
553 var digest []byte
554 var hashFunc crypto.Hash
David Benjamine098ec22014-08-27 23:13:20 -0400555 digest, hashFunc, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400556 if err != nil {
557 break
558 }
Adam Langley95c29f32014-06-20 12:00:00 -0700559 err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)
560 }
561 if err != nil {
562 c.sendAlert(alertBadCertificate)
563 return errors.New("could not validate signature of connection nonces: " + err.Error())
564 }
565
David Benjamin83c0bc92014-08-04 01:23:53 -0400566 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700567 }
568
David Benjamine098ec22014-08-27 23:13:20 -0400569 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -0700570
571 return nil
572}
573
574func (hs *serverHandshakeState) establishKeys() error {
575 c := hs.c
576
577 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
578 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
579
580 var clientCipher, serverCipher interface{}
581 var clientHash, serverHash macFunction
582
583 if hs.suite.aead == nil {
584 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
585 clientHash = hs.suite.mac(c.vers, clientMAC)
586 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
587 serverHash = hs.suite.mac(c.vers, serverMAC)
588 } else {
589 clientCipher = hs.suite.aead(clientKey, clientIV)
590 serverCipher = hs.suite.aead(serverKey, serverIV)
591 }
592
593 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
594 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
595
596 return nil
597}
598
David Benjamind30a9902014-08-24 01:44:23 -0400599func (hs *serverHandshakeState) readFinished(isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700600 c := hs.c
601
602 c.readRecord(recordTypeChangeCipherSpec)
603 if err := c.in.error(); err != nil {
604 return err
605 }
606
607 if hs.hello.nextProtoNeg {
608 msg, err := c.readHandshake()
609 if err != nil {
610 return err
611 }
612 nextProto, ok := msg.(*nextProtoMsg)
613 if !ok {
614 c.sendAlert(alertUnexpectedMessage)
615 return unexpectedMessageError(nextProto, msg)
616 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400617 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700618 c.clientProtocol = nextProto.proto
619 }
620
David Benjamind30a9902014-08-24 01:44:23 -0400621 if hs.hello.channelIDRequested {
622 msg, err := c.readHandshake()
623 if err != nil {
624 return err
625 }
626 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
627 if !ok {
628 c.sendAlert(alertUnexpectedMessage)
629 return unexpectedMessageError(encryptedExtensions, msg)
630 }
631 x := new(big.Int).SetBytes(encryptedExtensions.channelID[0:32])
632 y := new(big.Int).SetBytes(encryptedExtensions.channelID[32:64])
633 r := new(big.Int).SetBytes(encryptedExtensions.channelID[64:96])
634 s := new(big.Int).SetBytes(encryptedExtensions.channelID[96:128])
635 if !elliptic.P256().IsOnCurve(x, y) {
636 return errors.New("tls: invalid channel ID public key")
637 }
638 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
639 var resumeHash []byte
640 if isResume {
641 resumeHash = hs.sessionState.handshakeHash
642 }
643 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
644 return errors.New("tls: invalid channel ID signature")
645 }
646 c.channelID = channelID
647
648 hs.writeClientHash(encryptedExtensions.marshal())
649 }
650
Adam Langley95c29f32014-06-20 12:00:00 -0700651 msg, err := c.readHandshake()
652 if err != nil {
653 return err
654 }
655 clientFinished, ok := msg.(*finishedMsg)
656 if !ok {
657 c.sendAlert(alertUnexpectedMessage)
658 return unexpectedMessageError(clientFinished, msg)
659 }
660
661 verify := hs.finishedHash.clientSum(hs.masterSecret)
662 if len(verify) != len(clientFinished.verifyData) ||
663 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
664 c.sendAlert(alertHandshakeFailure)
665 return errors.New("tls: client's Finished message is incorrect")
666 }
667
David Benjamin83c0bc92014-08-04 01:23:53 -0400668 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700669 return nil
670}
671
672func (hs *serverHandshakeState) sendSessionTicket() error {
David Benjamind23f4122014-07-23 15:09:48 -0400673 if !hs.hello.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
Adam Langley95c29f32014-06-20 12:00:00 -0700674 return nil
675 }
676
677 c := hs.c
678 m := new(newSessionTicketMsg)
679
680 var err error
681 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -0400682 vers: c.vers,
683 cipherSuite: hs.suite.id,
684 masterSecret: hs.masterSecret,
685 certificates: hs.certsFromClient,
686 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -0700687 }
688 m.ticket, err = c.encryptTicket(&state)
689 if err != nil {
690 return err
691 }
Adam Langley95c29f32014-06-20 12:00:00 -0700692
David Benjamin83c0bc92014-08-04 01:23:53 -0400693 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700694 c.writeRecord(recordTypeHandshake, m.marshal())
695
696 return nil
697}
698
699func (hs *serverHandshakeState) sendFinished() error {
700 c := hs.c
701
David Benjamin86271ee2014-07-21 16:14:03 -0400702 finished := new(finishedMsg)
703 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
704 postCCSBytes := finished.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -0400705 hs.writeServerHash(postCCSBytes)
David Benjamin86271ee2014-07-21 16:14:03 -0400706
707 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
708 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
709 postCCSBytes = postCCSBytes[5:]
710 }
711
David Benjamina0e52232014-07-19 17:39:58 -0400712 if !c.config.Bugs.SkipChangeCipherSpec {
713 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
714 }
Adam Langley95c29f32014-06-20 12:00:00 -0700715
David Benjamin86271ee2014-07-21 16:14:03 -0400716 c.writeRecord(recordTypeHandshake, postCCSBytes)
Adam Langley95c29f32014-06-20 12:00:00 -0700717
718 c.cipherSuite = hs.suite.id
719
720 return nil
721}
722
723// processCertsFromClient takes a chain of client certificates either from a
724// Certificates message or from a sessionState and verifies them. It returns
725// the public key of the leaf certificate.
726func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
727 c := hs.c
728
729 hs.certsFromClient = certificates
730 certs := make([]*x509.Certificate, len(certificates))
731 var err error
732 for i, asn1Data := range certificates {
733 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
734 c.sendAlert(alertBadCertificate)
735 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
736 }
737 }
738
739 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
740 opts := x509.VerifyOptions{
741 Roots: c.config.ClientCAs,
742 CurrentTime: c.config.time(),
743 Intermediates: x509.NewCertPool(),
744 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
745 }
746
747 for _, cert := range certs[1:] {
748 opts.Intermediates.AddCert(cert)
749 }
750
751 chains, err := certs[0].Verify(opts)
752 if err != nil {
753 c.sendAlert(alertBadCertificate)
754 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
755 }
756
757 ok := false
758 for _, ku := range certs[0].ExtKeyUsage {
759 if ku == x509.ExtKeyUsageClientAuth {
760 ok = true
761 break
762 }
763 }
764 if !ok {
765 c.sendAlert(alertHandshakeFailure)
766 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
767 }
768
769 c.verifiedChains = chains
770 }
771
772 if len(certs) > 0 {
773 var pub crypto.PublicKey
774 switch key := certs[0].PublicKey.(type) {
775 case *ecdsa.PublicKey, *rsa.PublicKey:
776 pub = key
777 default:
778 c.sendAlert(alertUnsupportedCertificate)
779 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
780 }
781 c.peerCertificates = certs
782 return pub, nil
783 }
784
785 return nil, nil
786}
787
David Benjamin83c0bc92014-08-04 01:23:53 -0400788func (hs *serverHandshakeState) writeServerHash(msg []byte) {
789 // writeServerHash is called before writeRecord.
790 hs.writeHash(msg, hs.c.sendHandshakeSeq)
791}
792
793func (hs *serverHandshakeState) writeClientHash(msg []byte) {
794 // writeClientHash is called after readHandshake.
795 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
796}
797
798func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
799 if hs.c.isDTLS {
800 // This is somewhat hacky. DTLS hashes a slightly different format.
801 // First, the TLS header.
802 hs.finishedHash.Write(msg[:4])
803 // Then the sequence number and reassembled fragment offset (always 0).
804 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
805 // Then the reassembled fragment (always equal to the message length).
806 hs.finishedHash.Write(msg[1:4])
807 // And then the message body.
808 hs.finishedHash.Write(msg[4:])
809 } else {
810 hs.finishedHash.Write(msg)
811 }
812}
813
Adam Langley95c29f32014-06-20 12:00:00 -0700814// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
815// is acceptable to use.
816func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
817 for _, supported := range supportedCipherSuites {
818 if id == supported {
819 var candidate *cipherSuite
820
821 for _, s := range cipherSuites {
822 if s.id == id {
823 candidate = s
824 break
825 }
826 }
827 if candidate == nil {
828 continue
829 }
830 // Don't select a ciphersuite which we can't
831 // support for this client.
832 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
833 continue
834 }
835 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
836 continue
837 }
David Benjamin39ebf532014-08-31 02:23:49 -0400838 if !c.config.Bugs.SkipCipherVersionCheck && version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700839 continue
840 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400841 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
842 continue
843 }
Adam Langley95c29f32014-06-20 12:00:00 -0700844 return candidate
845 }
846 }
847
848 return nil
849}