blob: 3a54eb24268585c99d83348e9b4f78bd9c267167 [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 }
116 c.vers, ok = config.mutualVersion(hs.clientHello.vers)
117 if !ok {
118 c.sendAlert(alertProtocolVersion)
119 return false, fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
120 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400121
122 if c.isDTLS && !config.Bugs.SkipHelloVerifyRequest {
123 helloVerifyRequest := &helloVerifyRequestMsg{
124 vers: c.vers,
125 cookie: make([]byte, 32),
126 }
127 if _, err := io.ReadFull(c.config.rand(), helloVerifyRequest.cookie); err != nil {
128 c.sendAlert(alertInternalError)
129 return false, errors.New("dtls: short read from Rand: " + err.Error())
130 }
131 c.writeRecord(recordTypeHandshake, helloVerifyRequest.marshal())
132
133 msg, err := c.readHandshake()
134 if err != nil {
135 return false, err
136 }
137 newClientHello, ok := msg.(*clientHelloMsg)
138 if !ok {
139 c.sendAlert(alertUnexpectedMessage)
140 return false, unexpectedMessageError(hs.clientHello, msg)
141 }
142 if !bytes.Equal(newClientHello.cookie, helloVerifyRequest.cookie) {
143 return false, errors.New("dtls: invalid cookie")
144 }
145 // Apart from the cookie, client hello must match.
146 hs.clientHello.cookie = newClientHello.cookie
147 if hs.clientHello.equal(newClientHello) {
148 return false, errors.New("dtls: retransmitted ClientHello does not match")
149 }
150 hs.clientHello = newClientHello
151 }
152
153 // Do not set c.haveVers until after HelloVerifyRequest; the
154 // retransmitted ClientHello may not have the final version.
Adam Langley95c29f32014-06-20 12:00:00 -0700155 c.haveVers = true
156
157 hs.hello = new(serverHelloMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400158 hs.hello.isDTLS = c.isDTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700159
160 supportedCurve := false
161 preferredCurves := config.curvePreferences()
162Curves:
163 for _, curve := range hs.clientHello.supportedCurves {
164 for _, supported := range preferredCurves {
165 if supported == curve {
166 supportedCurve = true
167 break Curves
168 }
169 }
170 }
171
172 supportedPointFormat := false
173 for _, pointFormat := range hs.clientHello.supportedPoints {
174 if pointFormat == pointFormatUncompressed {
175 supportedPointFormat = true
176 break
177 }
178 }
179 hs.ellipticOk = supportedCurve && supportedPointFormat
180
181 foundCompression := false
182 // We only support null compression, so check that the client offered it.
183 for _, compression := range hs.clientHello.compressionMethods {
184 if compression == compressionNone {
185 foundCompression = true
186 break
187 }
188 }
189
190 if !foundCompression {
191 c.sendAlert(alertHandshakeFailure)
192 return false, errors.New("tls: client does not support uncompressed connections")
193 }
194
195 hs.hello.vers = c.vers
196 hs.hello.random = make([]byte, 32)
197 _, err = io.ReadFull(config.rand(), hs.hello.random)
198 if err != nil {
199 c.sendAlert(alertInternalError)
200 return false, err
201 }
202 hs.hello.secureRenegotiation = hs.clientHello.secureRenegotiation
203 hs.hello.compressionMethod = compressionNone
David Benjamin35a7a442014-07-05 00:23:20 -0400204 hs.hello.duplicateExtension = c.config.Bugs.DuplicateExtension
Adam Langley95c29f32014-06-20 12:00:00 -0700205 if len(hs.clientHello.serverName) > 0 {
206 c.serverName = hs.clientHello.serverName
207 }
208 // Although sending an empty NPN extension is reasonable, Firefox has
209 // had a bug around this. Best to send nothing at all if
210 // config.NextProtos is empty. See
211 // https://code.google.com/p/go/issues/detail?id=5445.
212 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
213 hs.hello.nextProtoNeg = true
214 hs.hello.nextProtos = config.NextProtos
215 }
216
217 if len(config.Certificates) == 0 {
218 c.sendAlert(alertInternalError)
219 return false, errors.New("tls: no certificates configured")
220 }
221 hs.cert = &config.Certificates[0]
222 if len(hs.clientHello.serverName) > 0 {
223 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
224 }
225
226 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
227
228 if hs.checkForResumption() {
229 return true, nil
230 }
231
Adam Langleyac61fa32014-06-23 12:03:11 -0700232 var scsvFound bool
233
234 for _, cipherSuite := range hs.clientHello.cipherSuites {
235 if cipherSuite == fallbackSCSV {
236 scsvFound = true
237 break
238 }
239 }
240
241 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
242 return false, errors.New("tls: no fallback SCSV found when expected")
243 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
244 return false, errors.New("tls: fallback SCSV found when not expected")
245 }
246
Adam Langley95c29f32014-06-20 12:00:00 -0700247 var preferenceList, supportedList []uint16
248 if c.config.PreferServerCipherSuites {
249 preferenceList = c.config.cipherSuites()
250 supportedList = hs.clientHello.cipherSuites
251 } else {
252 preferenceList = hs.clientHello.cipherSuites
253 supportedList = c.config.cipherSuites()
254 }
255
256 for _, id := range preferenceList {
257 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
258 break
259 }
260 }
261
262 if hs.suite == nil {
263 c.sendAlert(alertHandshakeFailure)
264 return false, errors.New("tls: no cipher suite supported by both client and server")
265 }
266
267 return false, nil
268}
269
270// checkForResumption returns true if we should perform resumption on this connection.
271func (hs *serverHandshakeState) checkForResumption() bool {
272 c := hs.c
273
274 var ok bool
275 if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
276 return false
277 }
278
279 if hs.sessionState.vers > hs.clientHello.vers {
280 return false
281 }
282 if vers, ok := c.config.mutualVersion(hs.sessionState.vers); !ok || vers != hs.sessionState.vers {
283 return false
284 }
285
286 cipherSuiteOk := false
287 // Check that the client is still offering the ciphersuite in the session.
288 for _, id := range hs.clientHello.cipherSuites {
289 if id == hs.sessionState.cipherSuite {
290 cipherSuiteOk = true
291 break
292 }
293 }
294 if !cipherSuiteOk {
295 return false
296 }
297
298 // Check that we also support the ciphersuite from the session.
299 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk)
300 if hs.suite == nil {
301 return false
302 }
303
304 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
305 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
306 if needClientCerts && !sessionHasClientCerts {
307 return false
308 }
309 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
310 return false
311 }
312
313 return true
314}
315
316func (hs *serverHandshakeState) doResumeHandshake() error {
317 c := hs.c
318
319 hs.hello.cipherSuite = hs.suite.id
320 // We echo the client's session ID in the ServerHello to let it know
321 // that we're doing a resumption.
322 hs.hello.sessionId = hs.clientHello.sessionId
David Benjaminbed9aae2014-08-07 19:13:38 -0400323 hs.hello.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -0700324
325 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400326 hs.writeClientHash(hs.clientHello.marshal())
327 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700328
329 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
330
331 if len(hs.sessionState.certificates) > 0 {
332 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
333 return err
334 }
335 }
336
337 hs.masterSecret = hs.sessionState.masterSecret
338
339 return nil
340}
341
342func (hs *serverHandshakeState) doFullHandshake() error {
343 config := hs.c.config
344 c := hs.c
345
346 if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
347 hs.hello.ocspStapling = true
348 }
349
350 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled
351 hs.hello.cipherSuite = hs.suite.id
352
353 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400354 hs.writeClientHash(hs.clientHello.marshal())
355 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700356
357 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
358
359 certMsg := new(certificateMsg)
360 certMsg.certificates = hs.cert.Certificate
David Benjamin1c375dd2014-07-12 00:48:23 -0400361 if !config.Bugs.UnauthenticatedECDH {
David Benjamin83c0bc92014-08-04 01:23:53 -0400362 hs.writeServerHash(certMsg.marshal())
David Benjamin1c375dd2014-07-12 00:48:23 -0400363 c.writeRecord(recordTypeHandshake, certMsg.marshal())
364 }
Adam Langley95c29f32014-06-20 12:00:00 -0700365
366 if hs.hello.ocspStapling {
367 certStatus := new(certificateStatusMsg)
368 certStatus.statusType = statusTypeOCSP
369 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -0400370 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700371 c.writeRecord(recordTypeHandshake, certStatus.marshal())
372 }
373
374 keyAgreement := hs.suite.ka(c.vers)
375 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
376 if err != nil {
377 c.sendAlert(alertHandshakeFailure)
378 return err
379 }
David Benjamin9c651c92014-07-12 13:27:45 -0400380 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -0400381 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700382 c.writeRecord(recordTypeHandshake, skx.marshal())
383 }
384
385 if config.ClientAuth >= RequestClientCert {
386 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -0400387 certReq := &certificateRequestMsg{
388 certificateTypes: config.ClientCertificateTypes,
389 }
390 if certReq.certificateTypes == nil {
391 certReq.certificateTypes = []byte{
392 byte(CertTypeRSASign),
393 byte(CertTypeECDSASign),
394 }
Adam Langley95c29f32014-06-20 12:00:00 -0700395 }
396 if c.vers >= VersionTLS12 {
397 certReq.hasSignatureAndHash = true
398 certReq.signatureAndHashes = supportedClientCertSignatureAlgorithms
399 }
400
401 // An empty list of certificateAuthorities signals to
402 // the client that it may send any certificate in response
403 // to our request. When we know the CAs we trust, then
404 // we can send them down, so that the client can choose
405 // an appropriate certificate to give to us.
406 if config.ClientCAs != nil {
407 certReq.certificateAuthorities = config.ClientCAs.Subjects()
408 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400409 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700410 c.writeRecord(recordTypeHandshake, certReq.marshal())
411 }
412
413 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400414 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700415 c.writeRecord(recordTypeHandshake, helloDone.marshal())
416
417 var pub crypto.PublicKey // public key for client auth, if any
418
419 msg, err := c.readHandshake()
420 if err != nil {
421 return err
422 }
423
424 var ok bool
425 // If we requested a client certificate, then the client must send a
426 // certificate message, even if it's empty.
427 if config.ClientAuth >= RequestClientCert {
428 if certMsg, ok = msg.(*certificateMsg); !ok {
429 c.sendAlert(alertUnexpectedMessage)
430 return unexpectedMessageError(certMsg, msg)
431 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400432 hs.writeClientHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700433
434 if len(certMsg.certificates) == 0 {
435 // The client didn't actually send a certificate
436 switch config.ClientAuth {
437 case RequireAnyClientCert, RequireAndVerifyClientCert:
438 c.sendAlert(alertBadCertificate)
439 return errors.New("tls: client didn't provide a certificate")
440 }
441 }
442
443 pub, err = hs.processCertsFromClient(certMsg.certificates)
444 if err != nil {
445 return err
446 }
447
448 msg, err = c.readHandshake()
449 if err != nil {
450 return err
451 }
452 }
453
454 // Get client key exchange
455 ckx, ok := msg.(*clientKeyExchangeMsg)
456 if !ok {
457 c.sendAlert(alertUnexpectedMessage)
458 return unexpectedMessageError(ckx, msg)
459 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400460 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700461
462 // If we received a client cert in response to our certificate request message,
463 // the client will send us a certificateVerifyMsg immediately after the
464 // clientKeyExchangeMsg. This message is a digest of all preceding
465 // handshake-layer messages that is signed using the private key corresponding
466 // to the client's certificate. This allows us to verify that the client is in
467 // possession of the private key of the certificate.
468 if len(c.peerCertificates) > 0 {
469 msg, err = c.readHandshake()
470 if err != nil {
471 return err
472 }
473 certVerify, ok := msg.(*certificateVerifyMsg)
474 if !ok {
475 c.sendAlert(alertUnexpectedMessage)
476 return unexpectedMessageError(certVerify, msg)
477 }
478
David Benjaminde620d92014-07-18 15:03:41 -0400479 // Determine the signature type.
480 var signatureAndHash signatureAndHash
481 if certVerify.hasSignatureAndHash {
482 signatureAndHash = certVerify.signatureAndHash
483 } else {
484 // Before TLS 1.2 the signature algorithm was implicit
485 // from the key type, and only one hash per signature
486 // algorithm was possible. Leave the hash as zero.
487 switch pub.(type) {
488 case *ecdsa.PublicKey:
489 signatureAndHash.signature = signatureECDSA
490 case *rsa.PublicKey:
491 signatureAndHash.signature = signatureRSA
492 }
493 }
494
Adam Langley95c29f32014-06-20 12:00:00 -0700495 switch key := pub.(type) {
496 case *ecdsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400497 if signatureAndHash.signature != signatureECDSA {
498 err = errors.New("tls: bad signature type for client's ECDSA certificate")
499 break
500 }
Adam Langley95c29f32014-06-20 12:00:00 -0700501 ecdsaSig := new(ecdsaSignature)
502 if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {
503 break
504 }
505 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
506 err = errors.New("ECDSA signature contained zero or negative values")
507 break
508 }
David Benjaminde620d92014-07-18 15:03:41 -0400509 var digest []byte
510 digest, _, err = hs.finishedHash.hashForClientCertificate(signatureAndHash)
511 if err != nil {
512 break
513 }
Adam Langley95c29f32014-06-20 12:00:00 -0700514 if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {
515 err = errors.New("ECDSA verification failure")
516 break
517 }
518 case *rsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400519 if signatureAndHash.signature != signatureRSA {
520 err = errors.New("tls: bad signature type for client's RSA certificate")
521 break
522 }
523 var digest []byte
524 var hashFunc crypto.Hash
525 digest, hashFunc, err = hs.finishedHash.hashForClientCertificate(signatureAndHash)
526 if err != nil {
527 break
528 }
Adam Langley95c29f32014-06-20 12:00:00 -0700529 err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)
530 }
531 if err != nil {
532 c.sendAlert(alertBadCertificate)
533 return errors.New("could not validate signature of connection nonces: " + err.Error())
534 }
535
David Benjamin83c0bc92014-08-04 01:23:53 -0400536 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700537 }
538
539 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
540 if err != nil {
541 c.sendAlert(alertHandshakeFailure)
542 return err
543 }
544 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
545
546 return nil
547}
548
549func (hs *serverHandshakeState) establishKeys() error {
550 c := hs.c
551
552 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
553 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
554
555 var clientCipher, serverCipher interface{}
556 var clientHash, serverHash macFunction
557
558 if hs.suite.aead == nil {
559 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
560 clientHash = hs.suite.mac(c.vers, clientMAC)
561 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
562 serverHash = hs.suite.mac(c.vers, serverMAC)
563 } else {
564 clientCipher = hs.suite.aead(clientKey, clientIV)
565 serverCipher = hs.suite.aead(serverKey, serverIV)
566 }
567
568 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
569 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
570
571 return nil
572}
573
574func (hs *serverHandshakeState) readFinished() error {
575 c := hs.c
576
577 c.readRecord(recordTypeChangeCipherSpec)
578 if err := c.in.error(); err != nil {
579 return err
580 }
581
582 if hs.hello.nextProtoNeg {
583 msg, err := c.readHandshake()
584 if err != nil {
585 return err
586 }
587 nextProto, ok := msg.(*nextProtoMsg)
588 if !ok {
589 c.sendAlert(alertUnexpectedMessage)
590 return unexpectedMessageError(nextProto, msg)
591 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400592 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700593 c.clientProtocol = nextProto.proto
594 }
595
596 msg, err := c.readHandshake()
597 if err != nil {
598 return err
599 }
600 clientFinished, ok := msg.(*finishedMsg)
601 if !ok {
602 c.sendAlert(alertUnexpectedMessage)
603 return unexpectedMessageError(clientFinished, msg)
604 }
605
606 verify := hs.finishedHash.clientSum(hs.masterSecret)
607 if len(verify) != len(clientFinished.verifyData) ||
608 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
609 c.sendAlert(alertHandshakeFailure)
610 return errors.New("tls: client's Finished message is incorrect")
611 }
612
David Benjamin83c0bc92014-08-04 01:23:53 -0400613 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700614 return nil
615}
616
617func (hs *serverHandshakeState) sendSessionTicket() error {
David Benjamind23f4122014-07-23 15:09:48 -0400618 if !hs.hello.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
Adam Langley95c29f32014-06-20 12:00:00 -0700619 return nil
620 }
621
622 c := hs.c
623 m := new(newSessionTicketMsg)
624
625 var err error
626 state := sessionState{
627 vers: c.vers,
628 cipherSuite: hs.suite.id,
629 masterSecret: hs.masterSecret,
630 certificates: hs.certsFromClient,
631 }
632 m.ticket, err = c.encryptTicket(&state)
633 if err != nil {
634 return err
635 }
Adam Langley95c29f32014-06-20 12:00:00 -0700636
David Benjamin83c0bc92014-08-04 01:23:53 -0400637 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700638 c.writeRecord(recordTypeHandshake, m.marshal())
639
640 return nil
641}
642
643func (hs *serverHandshakeState) sendFinished() error {
644 c := hs.c
645
David Benjamin86271ee2014-07-21 16:14:03 -0400646 finished := new(finishedMsg)
647 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
648 postCCSBytes := finished.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -0400649 hs.writeServerHash(postCCSBytes)
David Benjamin86271ee2014-07-21 16:14:03 -0400650
651 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
652 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
653 postCCSBytes = postCCSBytes[5:]
654 }
655
David Benjamina0e52232014-07-19 17:39:58 -0400656 if !c.config.Bugs.SkipChangeCipherSpec {
657 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
658 }
Adam Langley95c29f32014-06-20 12:00:00 -0700659
David Benjamin86271ee2014-07-21 16:14:03 -0400660 c.writeRecord(recordTypeHandshake, postCCSBytes)
Adam Langley95c29f32014-06-20 12:00:00 -0700661
662 c.cipherSuite = hs.suite.id
663
664 return nil
665}
666
667// processCertsFromClient takes a chain of client certificates either from a
668// Certificates message or from a sessionState and verifies them. It returns
669// the public key of the leaf certificate.
670func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
671 c := hs.c
672
673 hs.certsFromClient = certificates
674 certs := make([]*x509.Certificate, len(certificates))
675 var err error
676 for i, asn1Data := range certificates {
677 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
678 c.sendAlert(alertBadCertificate)
679 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
680 }
681 }
682
683 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
684 opts := x509.VerifyOptions{
685 Roots: c.config.ClientCAs,
686 CurrentTime: c.config.time(),
687 Intermediates: x509.NewCertPool(),
688 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
689 }
690
691 for _, cert := range certs[1:] {
692 opts.Intermediates.AddCert(cert)
693 }
694
695 chains, err := certs[0].Verify(opts)
696 if err != nil {
697 c.sendAlert(alertBadCertificate)
698 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
699 }
700
701 ok := false
702 for _, ku := range certs[0].ExtKeyUsage {
703 if ku == x509.ExtKeyUsageClientAuth {
704 ok = true
705 break
706 }
707 }
708 if !ok {
709 c.sendAlert(alertHandshakeFailure)
710 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
711 }
712
713 c.verifiedChains = chains
714 }
715
716 if len(certs) > 0 {
717 var pub crypto.PublicKey
718 switch key := certs[0].PublicKey.(type) {
719 case *ecdsa.PublicKey, *rsa.PublicKey:
720 pub = key
721 default:
722 c.sendAlert(alertUnsupportedCertificate)
723 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
724 }
725 c.peerCertificates = certs
726 return pub, nil
727 }
728
729 return nil, nil
730}
731
David Benjamin83c0bc92014-08-04 01:23:53 -0400732func (hs *serverHandshakeState) writeServerHash(msg []byte) {
733 // writeServerHash is called before writeRecord.
734 hs.writeHash(msg, hs.c.sendHandshakeSeq)
735}
736
737func (hs *serverHandshakeState) writeClientHash(msg []byte) {
738 // writeClientHash is called after readHandshake.
739 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
740}
741
742func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
743 if hs.c.isDTLS {
744 // This is somewhat hacky. DTLS hashes a slightly different format.
745 // First, the TLS header.
746 hs.finishedHash.Write(msg[:4])
747 // Then the sequence number and reassembled fragment offset (always 0).
748 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
749 // Then the reassembled fragment (always equal to the message length).
750 hs.finishedHash.Write(msg[1:4])
751 // And then the message body.
752 hs.finishedHash.Write(msg[4:])
753 } else {
754 hs.finishedHash.Write(msg)
755 }
756}
757
Adam Langley95c29f32014-06-20 12:00:00 -0700758// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
759// is acceptable to use.
760func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
761 for _, supported := range supportedCipherSuites {
762 if id == supported {
763 var candidate *cipherSuite
764
765 for _, s := range cipherSuites {
766 if s.id == id {
767 candidate = s
768 break
769 }
770 }
771 if candidate == nil {
772 continue
773 }
774 // Don't select a ciphersuite which we can't
775 // support for this client.
776 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
777 continue
778 }
779 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
780 continue
781 }
782 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
783 continue
784 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400785 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
786 continue
787 }
Adam Langley95c29f32014-06-20 12:00:00 -0700788 return candidate
789 }
790 }
791
792 return nil
793}