blob: d5a660a8cc474ac8d7055265598d4cafb800c6ad [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"
11 "crypto/rsa"
12 "crypto/subtle"
13 "crypto/x509"
14 "encoding/asn1"
15 "errors"
16 "fmt"
17 "io"
18)
19
20// serverHandshakeState contains details of a server handshake in progress.
21// It's discarded once the handshake has completed.
22type serverHandshakeState struct {
23 c *Conn
24 clientHello *clientHelloMsg
25 hello *serverHelloMsg
26 suite *cipherSuite
27 ellipticOk bool
28 ecdsaOk bool
29 sessionState *sessionState
30 finishedHash finishedHash
31 masterSecret []byte
32 certsFromClient [][]byte
33 cert *Certificate
34}
35
36// serverHandshake performs a TLS handshake as a server.
37func (c *Conn) serverHandshake() error {
38 config := c.config
39
40 // If this is the first server handshake, we generate a random key to
41 // encrypt the tickets with.
42 config.serverInitOnce.Do(config.serverInit)
43
David Benjamin83c0bc92014-08-04 01:23:53 -040044 c.sendHandshakeSeq = 0
45 c.recvHandshakeSeq = 0
46
Adam Langley95c29f32014-06-20 12:00:00 -070047 hs := serverHandshakeState{
48 c: c,
49 }
50 isResume, err := hs.readClientHello()
51 if err != nil {
52 return err
53 }
54
55 // For an overview of TLS handshaking, see https://tools.ietf.org/html/rfc5246#section-7.3
56 if isResume {
57 // The client has included a session ticket and so we do an abbreviated handshake.
58 if err := hs.doResumeHandshake(); err != nil {
59 return err
60 }
61 if err := hs.establishKeys(); err != nil {
62 return err
63 }
David Benjaminbed9aae2014-08-07 19:13:38 -040064 if c.config.Bugs.RenewTicketOnResume {
65 if err := hs.sendSessionTicket(); err != nil {
66 return err
67 }
68 }
Adam Langley95c29f32014-06-20 12:00:00 -070069 if err := hs.sendFinished(); err != nil {
70 return err
71 }
72 if err := hs.readFinished(); err != nil {
73 return err
74 }
75 c.didResume = true
76 } else {
77 // The client didn't include a session ticket, or it wasn't
78 // valid so we do a full handshake.
79 if err := hs.doFullHandshake(); err != nil {
80 return err
81 }
82 if err := hs.establishKeys(); err != nil {
83 return err
84 }
85 if err := hs.readFinished(); err != nil {
86 return err
87 }
88 if err := hs.sendSessionTicket(); err != nil {
89 return err
90 }
91 if err := hs.sendFinished(); err != nil {
92 return err
93 }
94 }
95 c.handshakeComplete = true
96
97 return nil
98}
99
100// readClientHello reads a ClientHello message from the client and decides
101// whether we will perform session resumption.
102func (hs *serverHandshakeState) readClientHello() (isResume bool, err error) {
103 config := hs.c.config
104 c := hs.c
105
106 msg, err := c.readHandshake()
107 if err != nil {
108 return false, err
109 }
110 var ok bool
111 hs.clientHello, ok = msg.(*clientHelloMsg)
112 if !ok {
113 c.sendAlert(alertUnexpectedMessage)
114 return false, unexpectedMessageError(hs.clientHello, msg)
115 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400116
117 if c.isDTLS && !config.Bugs.SkipHelloVerifyRequest {
David Benjamin8bc38f52014-08-16 12:07:27 -0400118 // Per RFC 6347, the version field in HelloVerifyRequest SHOULD
119 // be always DTLS 1.0
David Benjamin83c0bc92014-08-04 01:23:53 -0400120 helloVerifyRequest := &helloVerifyRequestMsg{
David Benjamin8bc38f52014-08-16 12:07:27 -0400121 vers: VersionTLS10,
David Benjamin83c0bc92014-08-04 01:23:53 -0400122 cookie: make([]byte, 32),
123 }
124 if _, err := io.ReadFull(c.config.rand(), helloVerifyRequest.cookie); err != nil {
125 c.sendAlert(alertInternalError)
126 return false, errors.New("dtls: short read from Rand: " + err.Error())
127 }
128 c.writeRecord(recordTypeHandshake, helloVerifyRequest.marshal())
129
130 msg, err := c.readHandshake()
131 if err != nil {
132 return false, err
133 }
134 newClientHello, ok := msg.(*clientHelloMsg)
135 if !ok {
136 c.sendAlert(alertUnexpectedMessage)
137 return false, unexpectedMessageError(hs.clientHello, msg)
138 }
139 if !bytes.Equal(newClientHello.cookie, helloVerifyRequest.cookie) {
140 return false, errors.New("dtls: invalid cookie")
141 }
David Benjaminf2fedef2014-08-16 01:37:34 -0400142
143 // Apart from the cookie, the two ClientHellos must
144 // match. Note that clientHello.equal compares the
145 // serialization, so we make a copy.
146 oldClientHelloCopy := *hs.clientHello
147 oldClientHelloCopy.raw = nil
148 oldClientHelloCopy.cookie = nil
149 newClientHelloCopy := *newClientHello
150 newClientHelloCopy.raw = nil
151 newClientHelloCopy.cookie = nil
152 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400153 return false, errors.New("dtls: retransmitted ClientHello does not match")
154 }
155 hs.clientHello = newClientHello
156 }
157
David Benjamin8bc38f52014-08-16 12:07:27 -0400158 c.vers, ok = config.mutualVersion(hs.clientHello.vers)
159 if !ok {
160 c.sendAlert(alertProtocolVersion)
161 return false, fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
162 }
Adam Langley95c29f32014-06-20 12:00:00 -0700163 c.haveVers = true
164
165 hs.hello = new(serverHelloMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400166 hs.hello.isDTLS = c.isDTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700167
168 supportedCurve := false
169 preferredCurves := config.curvePreferences()
170Curves:
171 for _, curve := range hs.clientHello.supportedCurves {
172 for _, supported := range preferredCurves {
173 if supported == curve {
174 supportedCurve = true
175 break Curves
176 }
177 }
178 }
179
180 supportedPointFormat := false
181 for _, pointFormat := range hs.clientHello.supportedPoints {
182 if pointFormat == pointFormatUncompressed {
183 supportedPointFormat = true
184 break
185 }
186 }
187 hs.ellipticOk = supportedCurve && supportedPointFormat
188
189 foundCompression := false
190 // We only support null compression, so check that the client offered it.
191 for _, compression := range hs.clientHello.compressionMethods {
192 if compression == compressionNone {
193 foundCompression = true
194 break
195 }
196 }
197
198 if !foundCompression {
199 c.sendAlert(alertHandshakeFailure)
200 return false, errors.New("tls: client does not support uncompressed connections")
201 }
202
203 hs.hello.vers = c.vers
204 hs.hello.random = make([]byte, 32)
205 _, err = io.ReadFull(config.rand(), hs.hello.random)
206 if err != nil {
207 c.sendAlert(alertInternalError)
208 return false, err
209 }
210 hs.hello.secureRenegotiation = hs.clientHello.secureRenegotiation
211 hs.hello.compressionMethod = compressionNone
David Benjamin35a7a442014-07-05 00:23:20 -0400212 hs.hello.duplicateExtension = c.config.Bugs.DuplicateExtension
Adam Langley95c29f32014-06-20 12:00:00 -0700213 if len(hs.clientHello.serverName) > 0 {
214 c.serverName = hs.clientHello.serverName
215 }
216 // Although sending an empty NPN extension is reasonable, Firefox has
217 // had a bug around this. Best to send nothing at all if
218 // config.NextProtos is empty. See
219 // https://code.google.com/p/go/issues/detail?id=5445.
220 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
221 hs.hello.nextProtoNeg = true
222 hs.hello.nextProtos = config.NextProtos
223 }
224
225 if len(config.Certificates) == 0 {
226 c.sendAlert(alertInternalError)
227 return false, errors.New("tls: no certificates configured")
228 }
229 hs.cert = &config.Certificates[0]
230 if len(hs.clientHello.serverName) > 0 {
231 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
232 }
233
234 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
235
236 if hs.checkForResumption() {
237 return true, nil
238 }
239
Adam Langleyac61fa32014-06-23 12:03:11 -0700240 var scsvFound bool
241
242 for _, cipherSuite := range hs.clientHello.cipherSuites {
243 if cipherSuite == fallbackSCSV {
244 scsvFound = true
245 break
246 }
247 }
248
249 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
250 return false, errors.New("tls: no fallback SCSV found when expected")
251 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
252 return false, errors.New("tls: fallback SCSV found when not expected")
253 }
254
Adam Langley95c29f32014-06-20 12:00:00 -0700255 var preferenceList, supportedList []uint16
256 if c.config.PreferServerCipherSuites {
257 preferenceList = c.config.cipherSuites()
258 supportedList = hs.clientHello.cipherSuites
259 } else {
260 preferenceList = hs.clientHello.cipherSuites
261 supportedList = c.config.cipherSuites()
262 }
263
264 for _, id := range preferenceList {
265 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
266 break
267 }
268 }
269
270 if hs.suite == nil {
271 c.sendAlert(alertHandshakeFailure)
272 return false, errors.New("tls: no cipher suite supported by both client and server")
273 }
274
275 return false, nil
276}
277
278// checkForResumption returns true if we should perform resumption on this connection.
279func (hs *serverHandshakeState) checkForResumption() bool {
280 c := hs.c
281
282 var ok bool
283 if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
284 return false
285 }
286
287 if hs.sessionState.vers > hs.clientHello.vers {
288 return false
289 }
290 if vers, ok := c.config.mutualVersion(hs.sessionState.vers); !ok || vers != hs.sessionState.vers {
291 return false
292 }
293
294 cipherSuiteOk := false
295 // Check that the client is still offering the ciphersuite in the session.
296 for _, id := range hs.clientHello.cipherSuites {
297 if id == hs.sessionState.cipherSuite {
298 cipherSuiteOk = true
299 break
300 }
301 }
302 if !cipherSuiteOk {
303 return false
304 }
305
306 // Check that we also support the ciphersuite from the session.
307 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk)
308 if hs.suite == nil {
309 return false
310 }
311
312 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
313 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
314 if needClientCerts && !sessionHasClientCerts {
315 return false
316 }
317 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
318 return false
319 }
320
321 return true
322}
323
324func (hs *serverHandshakeState) doResumeHandshake() error {
325 c := hs.c
326
327 hs.hello.cipherSuite = hs.suite.id
328 // We echo the client's session ID in the ServerHello to let it know
329 // that we're doing a resumption.
330 hs.hello.sessionId = hs.clientHello.sessionId
David Benjaminbed9aae2014-08-07 19:13:38 -0400331 hs.hello.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -0700332
333 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400334 hs.writeClientHash(hs.clientHello.marshal())
335 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700336
337 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
338
339 if len(hs.sessionState.certificates) > 0 {
340 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
341 return err
342 }
343 }
344
345 hs.masterSecret = hs.sessionState.masterSecret
346
347 return nil
348}
349
350func (hs *serverHandshakeState) doFullHandshake() error {
351 config := hs.c.config
352 c := hs.c
353
354 if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
355 hs.hello.ocspStapling = true
356 }
357
358 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled
359 hs.hello.cipherSuite = hs.suite.id
360
361 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400362 hs.writeClientHash(hs.clientHello.marshal())
363 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700364
365 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
366
367 certMsg := new(certificateMsg)
368 certMsg.certificates = hs.cert.Certificate
David Benjamin1c375dd2014-07-12 00:48:23 -0400369 if !config.Bugs.UnauthenticatedECDH {
David Benjamin83c0bc92014-08-04 01:23:53 -0400370 hs.writeServerHash(certMsg.marshal())
David Benjamin1c375dd2014-07-12 00:48:23 -0400371 c.writeRecord(recordTypeHandshake, certMsg.marshal())
372 }
Adam Langley95c29f32014-06-20 12:00:00 -0700373
374 if hs.hello.ocspStapling {
375 certStatus := new(certificateStatusMsg)
376 certStatus.statusType = statusTypeOCSP
377 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -0400378 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700379 c.writeRecord(recordTypeHandshake, certStatus.marshal())
380 }
381
382 keyAgreement := hs.suite.ka(c.vers)
383 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
384 if err != nil {
385 c.sendAlert(alertHandshakeFailure)
386 return err
387 }
David Benjamin9c651c92014-07-12 13:27:45 -0400388 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -0400389 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700390 c.writeRecord(recordTypeHandshake, skx.marshal())
391 }
392
393 if config.ClientAuth >= RequestClientCert {
394 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -0400395 certReq := &certificateRequestMsg{
396 certificateTypes: config.ClientCertificateTypes,
397 }
398 if certReq.certificateTypes == nil {
399 certReq.certificateTypes = []byte{
400 byte(CertTypeRSASign),
401 byte(CertTypeECDSASign),
402 }
Adam Langley95c29f32014-06-20 12:00:00 -0700403 }
404 if c.vers >= VersionTLS12 {
405 certReq.hasSignatureAndHash = true
406 certReq.signatureAndHashes = supportedClientCertSignatureAlgorithms
407 }
408
409 // An empty list of certificateAuthorities signals to
410 // the client that it may send any certificate in response
411 // to our request. When we know the CAs we trust, then
412 // we can send them down, so that the client can choose
413 // an appropriate certificate to give to us.
414 if config.ClientCAs != nil {
415 certReq.certificateAuthorities = config.ClientCAs.Subjects()
416 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400417 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700418 c.writeRecord(recordTypeHandshake, certReq.marshal())
419 }
420
421 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400422 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700423 c.writeRecord(recordTypeHandshake, helloDone.marshal())
424
425 var pub crypto.PublicKey // public key for client auth, if any
426
427 msg, err := c.readHandshake()
428 if err != nil {
429 return err
430 }
431
432 var ok bool
433 // If we requested a client certificate, then the client must send a
434 // certificate message, even if it's empty.
435 if config.ClientAuth >= RequestClientCert {
436 if certMsg, ok = msg.(*certificateMsg); !ok {
437 c.sendAlert(alertUnexpectedMessage)
438 return unexpectedMessageError(certMsg, msg)
439 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400440 hs.writeClientHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700441
442 if len(certMsg.certificates) == 0 {
443 // The client didn't actually send a certificate
444 switch config.ClientAuth {
445 case RequireAnyClientCert, RequireAndVerifyClientCert:
446 c.sendAlert(alertBadCertificate)
447 return errors.New("tls: client didn't provide a certificate")
448 }
449 }
450
451 pub, err = hs.processCertsFromClient(certMsg.certificates)
452 if err != nil {
453 return err
454 }
455
456 msg, err = c.readHandshake()
457 if err != nil {
458 return err
459 }
460 }
461
462 // Get client key exchange
463 ckx, ok := msg.(*clientKeyExchangeMsg)
464 if !ok {
465 c.sendAlert(alertUnexpectedMessage)
466 return unexpectedMessageError(ckx, msg)
467 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400468 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700469
470 // If we received a client cert in response to our certificate request message,
471 // the client will send us a certificateVerifyMsg immediately after the
472 // clientKeyExchangeMsg. This message is a digest of all preceding
473 // handshake-layer messages that is signed using the private key corresponding
474 // to the client's certificate. This allows us to verify that the client is in
475 // possession of the private key of the certificate.
476 if len(c.peerCertificates) > 0 {
477 msg, err = c.readHandshake()
478 if err != nil {
479 return err
480 }
481 certVerify, ok := msg.(*certificateVerifyMsg)
482 if !ok {
483 c.sendAlert(alertUnexpectedMessage)
484 return unexpectedMessageError(certVerify, msg)
485 }
486
David Benjaminde620d92014-07-18 15:03:41 -0400487 // Determine the signature type.
488 var signatureAndHash signatureAndHash
489 if certVerify.hasSignatureAndHash {
490 signatureAndHash = certVerify.signatureAndHash
491 } else {
492 // Before TLS 1.2 the signature algorithm was implicit
493 // from the key type, and only one hash per signature
494 // algorithm was possible. Leave the hash as zero.
495 switch pub.(type) {
496 case *ecdsa.PublicKey:
497 signatureAndHash.signature = signatureECDSA
498 case *rsa.PublicKey:
499 signatureAndHash.signature = signatureRSA
500 }
501 }
502
Adam Langley95c29f32014-06-20 12:00:00 -0700503 switch key := pub.(type) {
504 case *ecdsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400505 if signatureAndHash.signature != signatureECDSA {
506 err = errors.New("tls: bad signature type for client's ECDSA certificate")
507 break
508 }
Adam Langley95c29f32014-06-20 12:00:00 -0700509 ecdsaSig := new(ecdsaSignature)
510 if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {
511 break
512 }
513 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
514 err = errors.New("ECDSA signature contained zero or negative values")
515 break
516 }
David Benjaminde620d92014-07-18 15:03:41 -0400517 var digest []byte
518 digest, _, err = hs.finishedHash.hashForClientCertificate(signatureAndHash)
519 if err != nil {
520 break
521 }
Adam Langley95c29f32014-06-20 12:00:00 -0700522 if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {
523 err = errors.New("ECDSA verification failure")
524 break
525 }
526 case *rsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400527 if signatureAndHash.signature != signatureRSA {
528 err = errors.New("tls: bad signature type for client's RSA certificate")
529 break
530 }
531 var digest []byte
532 var hashFunc crypto.Hash
533 digest, hashFunc, err = hs.finishedHash.hashForClientCertificate(signatureAndHash)
534 if err != nil {
535 break
536 }
Adam Langley95c29f32014-06-20 12:00:00 -0700537 err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)
538 }
539 if err != nil {
540 c.sendAlert(alertBadCertificate)
541 return errors.New("could not validate signature of connection nonces: " + err.Error())
542 }
543
David Benjamin83c0bc92014-08-04 01:23:53 -0400544 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700545 }
546
547 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
548 if err != nil {
549 c.sendAlert(alertHandshakeFailure)
550 return err
551 }
552 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
553
554 return nil
555}
556
557func (hs *serverHandshakeState) establishKeys() error {
558 c := hs.c
559
560 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
561 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
562
563 var clientCipher, serverCipher interface{}
564 var clientHash, serverHash macFunction
565
566 if hs.suite.aead == nil {
567 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
568 clientHash = hs.suite.mac(c.vers, clientMAC)
569 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
570 serverHash = hs.suite.mac(c.vers, serverMAC)
571 } else {
572 clientCipher = hs.suite.aead(clientKey, clientIV)
573 serverCipher = hs.suite.aead(serverKey, serverIV)
574 }
575
576 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
577 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
578
579 return nil
580}
581
582func (hs *serverHandshakeState) readFinished() error {
583 c := hs.c
584
585 c.readRecord(recordTypeChangeCipherSpec)
586 if err := c.in.error(); err != nil {
587 return err
588 }
589
590 if hs.hello.nextProtoNeg {
591 msg, err := c.readHandshake()
592 if err != nil {
593 return err
594 }
595 nextProto, ok := msg.(*nextProtoMsg)
596 if !ok {
597 c.sendAlert(alertUnexpectedMessage)
598 return unexpectedMessageError(nextProto, msg)
599 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400600 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700601 c.clientProtocol = nextProto.proto
602 }
603
604 msg, err := c.readHandshake()
605 if err != nil {
606 return err
607 }
608 clientFinished, ok := msg.(*finishedMsg)
609 if !ok {
610 c.sendAlert(alertUnexpectedMessage)
611 return unexpectedMessageError(clientFinished, msg)
612 }
613
614 verify := hs.finishedHash.clientSum(hs.masterSecret)
615 if len(verify) != len(clientFinished.verifyData) ||
616 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
617 c.sendAlert(alertHandshakeFailure)
618 return errors.New("tls: client's Finished message is incorrect")
619 }
620
David Benjamin83c0bc92014-08-04 01:23:53 -0400621 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700622 return nil
623}
624
625func (hs *serverHandshakeState) sendSessionTicket() error {
David Benjamind23f4122014-07-23 15:09:48 -0400626 if !hs.hello.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
Adam Langley95c29f32014-06-20 12:00:00 -0700627 return nil
628 }
629
630 c := hs.c
631 m := new(newSessionTicketMsg)
632
633 var err error
634 state := sessionState{
635 vers: c.vers,
636 cipherSuite: hs.suite.id,
637 masterSecret: hs.masterSecret,
638 certificates: hs.certsFromClient,
639 }
640 m.ticket, err = c.encryptTicket(&state)
641 if err != nil {
642 return err
643 }
Adam Langley95c29f32014-06-20 12:00:00 -0700644
David Benjamin83c0bc92014-08-04 01:23:53 -0400645 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700646 c.writeRecord(recordTypeHandshake, m.marshal())
647
648 return nil
649}
650
651func (hs *serverHandshakeState) sendFinished() error {
652 c := hs.c
653
David Benjamin86271ee2014-07-21 16:14:03 -0400654 finished := new(finishedMsg)
655 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
656 postCCSBytes := finished.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -0400657 hs.writeServerHash(postCCSBytes)
David Benjamin86271ee2014-07-21 16:14:03 -0400658
659 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
660 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
661 postCCSBytes = postCCSBytes[5:]
662 }
663
David Benjamina0e52232014-07-19 17:39:58 -0400664 if !c.config.Bugs.SkipChangeCipherSpec {
665 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
666 }
Adam Langley95c29f32014-06-20 12:00:00 -0700667
David Benjamin86271ee2014-07-21 16:14:03 -0400668 c.writeRecord(recordTypeHandshake, postCCSBytes)
Adam Langley95c29f32014-06-20 12:00:00 -0700669
670 c.cipherSuite = hs.suite.id
671
672 return nil
673}
674
675// processCertsFromClient takes a chain of client certificates either from a
676// Certificates message or from a sessionState and verifies them. It returns
677// the public key of the leaf certificate.
678func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
679 c := hs.c
680
681 hs.certsFromClient = certificates
682 certs := make([]*x509.Certificate, len(certificates))
683 var err error
684 for i, asn1Data := range certificates {
685 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
686 c.sendAlert(alertBadCertificate)
687 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
688 }
689 }
690
691 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
692 opts := x509.VerifyOptions{
693 Roots: c.config.ClientCAs,
694 CurrentTime: c.config.time(),
695 Intermediates: x509.NewCertPool(),
696 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
697 }
698
699 for _, cert := range certs[1:] {
700 opts.Intermediates.AddCert(cert)
701 }
702
703 chains, err := certs[0].Verify(opts)
704 if err != nil {
705 c.sendAlert(alertBadCertificate)
706 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
707 }
708
709 ok := false
710 for _, ku := range certs[0].ExtKeyUsage {
711 if ku == x509.ExtKeyUsageClientAuth {
712 ok = true
713 break
714 }
715 }
716 if !ok {
717 c.sendAlert(alertHandshakeFailure)
718 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
719 }
720
721 c.verifiedChains = chains
722 }
723
724 if len(certs) > 0 {
725 var pub crypto.PublicKey
726 switch key := certs[0].PublicKey.(type) {
727 case *ecdsa.PublicKey, *rsa.PublicKey:
728 pub = key
729 default:
730 c.sendAlert(alertUnsupportedCertificate)
731 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
732 }
733 c.peerCertificates = certs
734 return pub, nil
735 }
736
737 return nil, nil
738}
739
David Benjamin83c0bc92014-08-04 01:23:53 -0400740func (hs *serverHandshakeState) writeServerHash(msg []byte) {
741 // writeServerHash is called before writeRecord.
742 hs.writeHash(msg, hs.c.sendHandshakeSeq)
743}
744
745func (hs *serverHandshakeState) writeClientHash(msg []byte) {
746 // writeClientHash is called after readHandshake.
747 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
748}
749
750func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
751 if hs.c.isDTLS {
752 // This is somewhat hacky. DTLS hashes a slightly different format.
753 // First, the TLS header.
754 hs.finishedHash.Write(msg[:4])
755 // Then the sequence number and reassembled fragment offset (always 0).
756 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
757 // Then the reassembled fragment (always equal to the message length).
758 hs.finishedHash.Write(msg[1:4])
759 // And then the message body.
760 hs.finishedHash.Write(msg[4:])
761 } else {
762 hs.finishedHash.Write(msg)
763 }
764}
765
Adam Langley95c29f32014-06-20 12:00:00 -0700766// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
767// is acceptable to use.
768func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
769 for _, supported := range supportedCipherSuites {
770 if id == supported {
771 var candidate *cipherSuite
772
773 for _, s := range cipherSuites {
774 if s.id == id {
775 candidate = s
776 break
777 }
778 }
779 if candidate == nil {
780 continue
781 }
782 // Don't select a ciphersuite which we can't
783 // support for this client.
784 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
785 continue
786 }
787 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
788 continue
789 }
790 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
791 continue
792 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400793 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
794 continue
795 }
Adam Langley95c29f32014-06-20 12:00:00 -0700796 return candidate
797 }
798 }
799
800 return nil
801}