blob: 40e1b88a5982fe0c400d459a2fd820ef933893bf [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 }
90 if err := hs.sendSessionTicket(); err != nil {
91 return err
92 }
93 if err := hs.sendFinished(); err != nil {
94 return err
95 }
96 }
97 c.handshakeComplete = true
98
99 return nil
100}
101
102// readClientHello reads a ClientHello message from the client and decides
103// whether we will perform session resumption.
104func (hs *serverHandshakeState) readClientHello() (isResume bool, err error) {
105 config := hs.c.config
106 c := hs.c
107
108 msg, err := c.readHandshake()
109 if err != nil {
110 return false, err
111 }
112 var ok bool
113 hs.clientHello, ok = msg.(*clientHelloMsg)
114 if !ok {
115 c.sendAlert(alertUnexpectedMessage)
116 return false, unexpectedMessageError(hs.clientHello, msg)
117 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400118
119 if c.isDTLS && !config.Bugs.SkipHelloVerifyRequest {
David Benjamin8bc38f52014-08-16 12:07:27 -0400120 // Per RFC 6347, the version field in HelloVerifyRequest SHOULD
121 // be always DTLS 1.0
David Benjamin83c0bc92014-08-04 01:23:53 -0400122 helloVerifyRequest := &helloVerifyRequestMsg{
David Benjamin8bc38f52014-08-16 12:07:27 -0400123 vers: VersionTLS10,
David Benjamin83c0bc92014-08-04 01:23:53 -0400124 cookie: make([]byte, 32),
125 }
126 if _, err := io.ReadFull(c.config.rand(), helloVerifyRequest.cookie); err != nil {
127 c.sendAlert(alertInternalError)
128 return false, errors.New("dtls: short read from Rand: " + err.Error())
129 }
130 c.writeRecord(recordTypeHandshake, helloVerifyRequest.marshal())
131
132 msg, err := c.readHandshake()
133 if err != nil {
134 return false, err
135 }
136 newClientHello, ok := msg.(*clientHelloMsg)
137 if !ok {
138 c.sendAlert(alertUnexpectedMessage)
139 return false, unexpectedMessageError(hs.clientHello, msg)
140 }
141 if !bytes.Equal(newClientHello.cookie, helloVerifyRequest.cookie) {
142 return false, errors.New("dtls: invalid cookie")
143 }
David Benjaminf2fedef2014-08-16 01:37:34 -0400144
145 // Apart from the cookie, the two ClientHellos must
146 // match. Note that clientHello.equal compares the
147 // serialization, so we make a copy.
148 oldClientHelloCopy := *hs.clientHello
149 oldClientHelloCopy.raw = nil
150 oldClientHelloCopy.cookie = nil
151 newClientHelloCopy := *newClientHello
152 newClientHelloCopy.raw = nil
153 newClientHelloCopy.cookie = nil
154 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400155 return false, errors.New("dtls: retransmitted ClientHello does not match")
156 }
157 hs.clientHello = newClientHello
158 }
159
David Benjamin8bc38f52014-08-16 12:07:27 -0400160 c.vers, ok = config.mutualVersion(hs.clientHello.vers)
161 if !ok {
162 c.sendAlert(alertProtocolVersion)
163 return false, fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
164 }
Adam Langley95c29f32014-06-20 12:00:00 -0700165 c.haveVers = true
166
167 hs.hello = new(serverHelloMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400168 hs.hello.isDTLS = c.isDTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700169
170 supportedCurve := false
171 preferredCurves := config.curvePreferences()
172Curves:
173 for _, curve := range hs.clientHello.supportedCurves {
174 for _, supported := range preferredCurves {
175 if supported == curve {
176 supportedCurve = true
177 break Curves
178 }
179 }
180 }
181
182 supportedPointFormat := false
183 for _, pointFormat := range hs.clientHello.supportedPoints {
184 if pointFormat == pointFormatUncompressed {
185 supportedPointFormat = true
186 break
187 }
188 }
189 hs.ellipticOk = supportedCurve && supportedPointFormat
190
191 foundCompression := false
192 // We only support null compression, so check that the client offered it.
193 for _, compression := range hs.clientHello.compressionMethods {
194 if compression == compressionNone {
195 foundCompression = true
196 break
197 }
198 }
199
200 if !foundCompression {
201 c.sendAlert(alertHandshakeFailure)
202 return false, errors.New("tls: client does not support uncompressed connections")
203 }
204
205 hs.hello.vers = c.vers
206 hs.hello.random = make([]byte, 32)
207 _, err = io.ReadFull(config.rand(), hs.hello.random)
208 if err != nil {
209 c.sendAlert(alertInternalError)
210 return false, err
211 }
212 hs.hello.secureRenegotiation = hs.clientHello.secureRenegotiation
213 hs.hello.compressionMethod = compressionNone
David Benjamin35a7a442014-07-05 00:23:20 -0400214 hs.hello.duplicateExtension = c.config.Bugs.DuplicateExtension
Adam Langley95c29f32014-06-20 12:00:00 -0700215 if len(hs.clientHello.serverName) > 0 {
216 c.serverName = hs.clientHello.serverName
217 }
218 // Although sending an empty NPN extension is reasonable, Firefox has
219 // had a bug around this. Best to send nothing at all if
220 // config.NextProtos is empty. See
221 // https://code.google.com/p/go/issues/detail?id=5445.
222 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
223 hs.hello.nextProtoNeg = true
224 hs.hello.nextProtos = config.NextProtos
225 }
226
227 if len(config.Certificates) == 0 {
228 c.sendAlert(alertInternalError)
229 return false, errors.New("tls: no certificates configured")
230 }
231 hs.cert = &config.Certificates[0]
232 if len(hs.clientHello.serverName) > 0 {
233 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
234 }
235
David Benjamind30a9902014-08-24 01:44:23 -0400236 if hs.clientHello.channelIDSupported && config.RequestChannelID {
237 hs.hello.channelIDRequested = true
238 }
239
Adam Langley95c29f32014-06-20 12:00:00 -0700240 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
241
242 if hs.checkForResumption() {
243 return true, nil
244 }
245
Adam Langleyac61fa32014-06-23 12:03:11 -0700246 var scsvFound bool
247
248 for _, cipherSuite := range hs.clientHello.cipherSuites {
249 if cipherSuite == fallbackSCSV {
250 scsvFound = true
251 break
252 }
253 }
254
255 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
256 return false, errors.New("tls: no fallback SCSV found when expected")
257 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
258 return false, errors.New("tls: fallback SCSV found when not expected")
259 }
260
Adam Langley95c29f32014-06-20 12:00:00 -0700261 var preferenceList, supportedList []uint16
262 if c.config.PreferServerCipherSuites {
263 preferenceList = c.config.cipherSuites()
264 supportedList = hs.clientHello.cipherSuites
265 } else {
266 preferenceList = hs.clientHello.cipherSuites
267 supportedList = c.config.cipherSuites()
268 }
269
270 for _, id := range preferenceList {
271 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
272 break
273 }
274 }
275
276 if hs.suite == nil {
277 c.sendAlert(alertHandshakeFailure)
278 return false, errors.New("tls: no cipher suite supported by both client and server")
279 }
280
281 return false, nil
282}
283
284// checkForResumption returns true if we should perform resumption on this connection.
285func (hs *serverHandshakeState) checkForResumption() bool {
286 c := hs.c
287
288 var ok bool
289 if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
290 return false
291 }
292
293 if hs.sessionState.vers > hs.clientHello.vers {
294 return false
295 }
296 if vers, ok := c.config.mutualVersion(hs.sessionState.vers); !ok || vers != hs.sessionState.vers {
297 return false
298 }
299
300 cipherSuiteOk := false
301 // Check that the client is still offering the ciphersuite in the session.
302 for _, id := range hs.clientHello.cipherSuites {
303 if id == hs.sessionState.cipherSuite {
304 cipherSuiteOk = true
305 break
306 }
307 }
308 if !cipherSuiteOk {
309 return false
310 }
311
312 // Check that we also support the ciphersuite from the session.
313 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk)
314 if hs.suite == nil {
315 return false
316 }
317
318 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
319 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
320 if needClientCerts && !sessionHasClientCerts {
321 return false
322 }
323 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
324 return false
325 }
326
327 return true
328}
329
330func (hs *serverHandshakeState) doResumeHandshake() error {
331 c := hs.c
332
333 hs.hello.cipherSuite = hs.suite.id
334 // We echo the client's session ID in the ServerHello to let it know
335 // that we're doing a resumption.
336 hs.hello.sessionId = hs.clientHello.sessionId
David Benjaminbed9aae2014-08-07 19:13:38 -0400337 hs.hello.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -0700338
339 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400340 hs.writeClientHash(hs.clientHello.marshal())
341 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700342
343 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
344
345 if len(hs.sessionState.certificates) > 0 {
346 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
347 return err
348 }
349 }
350
351 hs.masterSecret = hs.sessionState.masterSecret
352
353 return nil
354}
355
356func (hs *serverHandshakeState) doFullHandshake() error {
357 config := hs.c.config
358 c := hs.c
359
360 if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
361 hs.hello.ocspStapling = true
362 }
363
364 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled
365 hs.hello.cipherSuite = hs.suite.id
366
367 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400368 hs.writeClientHash(hs.clientHello.marshal())
369 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700370
371 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
372
373 certMsg := new(certificateMsg)
374 certMsg.certificates = hs.cert.Certificate
David Benjamin1c375dd2014-07-12 00:48:23 -0400375 if !config.Bugs.UnauthenticatedECDH {
David Benjamin83c0bc92014-08-04 01:23:53 -0400376 hs.writeServerHash(certMsg.marshal())
David Benjamin1c375dd2014-07-12 00:48:23 -0400377 c.writeRecord(recordTypeHandshake, certMsg.marshal())
378 }
Adam Langley95c29f32014-06-20 12:00:00 -0700379
380 if hs.hello.ocspStapling {
381 certStatus := new(certificateStatusMsg)
382 certStatus.statusType = statusTypeOCSP
383 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -0400384 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700385 c.writeRecord(recordTypeHandshake, certStatus.marshal())
386 }
387
388 keyAgreement := hs.suite.ka(c.vers)
389 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
390 if err != nil {
391 c.sendAlert(alertHandshakeFailure)
392 return err
393 }
David Benjamin9c651c92014-07-12 13:27:45 -0400394 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -0400395 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700396 c.writeRecord(recordTypeHandshake, skx.marshal())
397 }
398
399 if config.ClientAuth >= RequestClientCert {
400 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -0400401 certReq := &certificateRequestMsg{
402 certificateTypes: config.ClientCertificateTypes,
403 }
404 if certReq.certificateTypes == nil {
405 certReq.certificateTypes = []byte{
406 byte(CertTypeRSASign),
407 byte(CertTypeECDSASign),
408 }
Adam Langley95c29f32014-06-20 12:00:00 -0700409 }
410 if c.vers >= VersionTLS12 {
411 certReq.hasSignatureAndHash = true
412 certReq.signatureAndHashes = supportedClientCertSignatureAlgorithms
413 }
414
415 // An empty list of certificateAuthorities signals to
416 // the client that it may send any certificate in response
417 // to our request. When we know the CAs we trust, then
418 // we can send them down, so that the client can choose
419 // an appropriate certificate to give to us.
420 if config.ClientCAs != nil {
421 certReq.certificateAuthorities = config.ClientCAs.Subjects()
422 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400423 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700424 c.writeRecord(recordTypeHandshake, certReq.marshal())
425 }
426
427 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400428 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700429 c.writeRecord(recordTypeHandshake, helloDone.marshal())
430
431 var pub crypto.PublicKey // public key for client auth, if any
432
433 msg, err := c.readHandshake()
434 if err != nil {
435 return err
436 }
437
438 var ok bool
439 // If we requested a client certificate, then the client must send a
440 // certificate message, even if it's empty.
441 if config.ClientAuth >= RequestClientCert {
442 if certMsg, ok = msg.(*certificateMsg); !ok {
443 c.sendAlert(alertUnexpectedMessage)
444 return unexpectedMessageError(certMsg, msg)
445 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400446 hs.writeClientHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700447
448 if len(certMsg.certificates) == 0 {
449 // The client didn't actually send a certificate
450 switch config.ClientAuth {
451 case RequireAnyClientCert, RequireAndVerifyClientCert:
452 c.sendAlert(alertBadCertificate)
453 return errors.New("tls: client didn't provide a certificate")
454 }
455 }
456
457 pub, err = hs.processCertsFromClient(certMsg.certificates)
458 if err != nil {
459 return err
460 }
461
462 msg, err = c.readHandshake()
463 if err != nil {
464 return err
465 }
466 }
467
468 // Get client key exchange
469 ckx, ok := msg.(*clientKeyExchangeMsg)
470 if !ok {
471 c.sendAlert(alertUnexpectedMessage)
472 return unexpectedMessageError(ckx, msg)
473 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400474 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700475
476 // If we received a client cert in response to our certificate request message,
477 // the client will send us a certificateVerifyMsg immediately after the
478 // clientKeyExchangeMsg. This message is a digest of all preceding
479 // handshake-layer messages that is signed using the private key corresponding
480 // to the client's certificate. This allows us to verify that the client is in
481 // possession of the private key of the certificate.
482 if len(c.peerCertificates) > 0 {
483 msg, err = c.readHandshake()
484 if err != nil {
485 return err
486 }
487 certVerify, ok := msg.(*certificateVerifyMsg)
488 if !ok {
489 c.sendAlert(alertUnexpectedMessage)
490 return unexpectedMessageError(certVerify, msg)
491 }
492
David Benjaminde620d92014-07-18 15:03:41 -0400493 // Determine the signature type.
494 var signatureAndHash signatureAndHash
495 if certVerify.hasSignatureAndHash {
496 signatureAndHash = certVerify.signatureAndHash
497 } else {
498 // Before TLS 1.2 the signature algorithm was implicit
499 // from the key type, and only one hash per signature
500 // algorithm was possible. Leave the hash as zero.
501 switch pub.(type) {
502 case *ecdsa.PublicKey:
503 signatureAndHash.signature = signatureECDSA
504 case *rsa.PublicKey:
505 signatureAndHash.signature = signatureRSA
506 }
507 }
508
Adam Langley95c29f32014-06-20 12:00:00 -0700509 switch key := pub.(type) {
510 case *ecdsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400511 if signatureAndHash.signature != signatureECDSA {
512 err = errors.New("tls: bad signature type for client's ECDSA certificate")
513 break
514 }
Adam Langley95c29f32014-06-20 12:00:00 -0700515 ecdsaSig := new(ecdsaSignature)
516 if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {
517 break
518 }
519 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
520 err = errors.New("ECDSA signature contained zero or negative values")
521 break
522 }
David Benjaminde620d92014-07-18 15:03:41 -0400523 var digest []byte
524 digest, _, err = hs.finishedHash.hashForClientCertificate(signatureAndHash)
525 if err != nil {
526 break
527 }
Adam Langley95c29f32014-06-20 12:00:00 -0700528 if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {
529 err = errors.New("ECDSA verification failure")
530 break
531 }
532 case *rsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400533 if signatureAndHash.signature != signatureRSA {
534 err = errors.New("tls: bad signature type for client's RSA certificate")
535 break
536 }
537 var digest []byte
538 var hashFunc crypto.Hash
539 digest, hashFunc, err = hs.finishedHash.hashForClientCertificate(signatureAndHash)
540 if err != nil {
541 break
542 }
Adam Langley95c29f32014-06-20 12:00:00 -0700543 err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)
544 }
545 if err != nil {
546 c.sendAlert(alertBadCertificate)
547 return errors.New("could not validate signature of connection nonces: " + err.Error())
548 }
549
David Benjamin83c0bc92014-08-04 01:23:53 -0400550 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700551 }
552
553 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
554 if err != nil {
555 c.sendAlert(alertHandshakeFailure)
556 return err
557 }
558 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
559
560 return nil
561}
562
563func (hs *serverHandshakeState) establishKeys() error {
564 c := hs.c
565
566 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
567 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
568
569 var clientCipher, serverCipher interface{}
570 var clientHash, serverHash macFunction
571
572 if hs.suite.aead == nil {
573 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
574 clientHash = hs.suite.mac(c.vers, clientMAC)
575 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
576 serverHash = hs.suite.mac(c.vers, serverMAC)
577 } else {
578 clientCipher = hs.suite.aead(clientKey, clientIV)
579 serverCipher = hs.suite.aead(serverKey, serverIV)
580 }
581
582 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
583 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
584
585 return nil
586}
587
David Benjamind30a9902014-08-24 01:44:23 -0400588func (hs *serverHandshakeState) readFinished(isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700589 c := hs.c
590
591 c.readRecord(recordTypeChangeCipherSpec)
592 if err := c.in.error(); err != nil {
593 return err
594 }
595
596 if hs.hello.nextProtoNeg {
597 msg, err := c.readHandshake()
598 if err != nil {
599 return err
600 }
601 nextProto, ok := msg.(*nextProtoMsg)
602 if !ok {
603 c.sendAlert(alertUnexpectedMessage)
604 return unexpectedMessageError(nextProto, msg)
605 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400606 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700607 c.clientProtocol = nextProto.proto
608 }
609
David Benjamind30a9902014-08-24 01:44:23 -0400610 if hs.hello.channelIDRequested {
611 msg, err := c.readHandshake()
612 if err != nil {
613 return err
614 }
615 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
616 if !ok {
617 c.sendAlert(alertUnexpectedMessage)
618 return unexpectedMessageError(encryptedExtensions, msg)
619 }
620 x := new(big.Int).SetBytes(encryptedExtensions.channelID[0:32])
621 y := new(big.Int).SetBytes(encryptedExtensions.channelID[32:64])
622 r := new(big.Int).SetBytes(encryptedExtensions.channelID[64:96])
623 s := new(big.Int).SetBytes(encryptedExtensions.channelID[96:128])
624 if !elliptic.P256().IsOnCurve(x, y) {
625 return errors.New("tls: invalid channel ID public key")
626 }
627 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
628 var resumeHash []byte
629 if isResume {
630 resumeHash = hs.sessionState.handshakeHash
631 }
632 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
633 return errors.New("tls: invalid channel ID signature")
634 }
635 c.channelID = channelID
636
637 hs.writeClientHash(encryptedExtensions.marshal())
638 }
639
Adam Langley95c29f32014-06-20 12:00:00 -0700640 msg, err := c.readHandshake()
641 if err != nil {
642 return err
643 }
644 clientFinished, ok := msg.(*finishedMsg)
645 if !ok {
646 c.sendAlert(alertUnexpectedMessage)
647 return unexpectedMessageError(clientFinished, msg)
648 }
649
650 verify := hs.finishedHash.clientSum(hs.masterSecret)
651 if len(verify) != len(clientFinished.verifyData) ||
652 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
653 c.sendAlert(alertHandshakeFailure)
654 return errors.New("tls: client's Finished message is incorrect")
655 }
656
David Benjamin83c0bc92014-08-04 01:23:53 -0400657 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700658 return nil
659}
660
661func (hs *serverHandshakeState) sendSessionTicket() error {
David Benjamind23f4122014-07-23 15:09:48 -0400662 if !hs.hello.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
Adam Langley95c29f32014-06-20 12:00:00 -0700663 return nil
664 }
665
666 c := hs.c
667 m := new(newSessionTicketMsg)
668
669 var err error
670 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -0400671 vers: c.vers,
672 cipherSuite: hs.suite.id,
673 masterSecret: hs.masterSecret,
674 certificates: hs.certsFromClient,
675 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -0700676 }
677 m.ticket, err = c.encryptTicket(&state)
678 if err != nil {
679 return err
680 }
Adam Langley95c29f32014-06-20 12:00:00 -0700681
David Benjamin83c0bc92014-08-04 01:23:53 -0400682 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700683 c.writeRecord(recordTypeHandshake, m.marshal())
684
685 return nil
686}
687
688func (hs *serverHandshakeState) sendFinished() error {
689 c := hs.c
690
David Benjamin86271ee2014-07-21 16:14:03 -0400691 finished := new(finishedMsg)
692 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
693 postCCSBytes := finished.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -0400694 hs.writeServerHash(postCCSBytes)
David Benjamin86271ee2014-07-21 16:14:03 -0400695
696 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
697 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
698 postCCSBytes = postCCSBytes[5:]
699 }
700
David Benjamina0e52232014-07-19 17:39:58 -0400701 if !c.config.Bugs.SkipChangeCipherSpec {
702 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
703 }
Adam Langley95c29f32014-06-20 12:00:00 -0700704
David Benjamin86271ee2014-07-21 16:14:03 -0400705 c.writeRecord(recordTypeHandshake, postCCSBytes)
Adam Langley95c29f32014-06-20 12:00:00 -0700706
707 c.cipherSuite = hs.suite.id
708
709 return nil
710}
711
712// processCertsFromClient takes a chain of client certificates either from a
713// Certificates message or from a sessionState and verifies them. It returns
714// the public key of the leaf certificate.
715func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
716 c := hs.c
717
718 hs.certsFromClient = certificates
719 certs := make([]*x509.Certificate, len(certificates))
720 var err error
721 for i, asn1Data := range certificates {
722 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
723 c.sendAlert(alertBadCertificate)
724 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
725 }
726 }
727
728 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
729 opts := x509.VerifyOptions{
730 Roots: c.config.ClientCAs,
731 CurrentTime: c.config.time(),
732 Intermediates: x509.NewCertPool(),
733 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
734 }
735
736 for _, cert := range certs[1:] {
737 opts.Intermediates.AddCert(cert)
738 }
739
740 chains, err := certs[0].Verify(opts)
741 if err != nil {
742 c.sendAlert(alertBadCertificate)
743 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
744 }
745
746 ok := false
747 for _, ku := range certs[0].ExtKeyUsage {
748 if ku == x509.ExtKeyUsageClientAuth {
749 ok = true
750 break
751 }
752 }
753 if !ok {
754 c.sendAlert(alertHandshakeFailure)
755 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
756 }
757
758 c.verifiedChains = chains
759 }
760
761 if len(certs) > 0 {
762 var pub crypto.PublicKey
763 switch key := certs[0].PublicKey.(type) {
764 case *ecdsa.PublicKey, *rsa.PublicKey:
765 pub = key
766 default:
767 c.sendAlert(alertUnsupportedCertificate)
768 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
769 }
770 c.peerCertificates = certs
771 return pub, nil
772 }
773
774 return nil, nil
775}
776
David Benjamin83c0bc92014-08-04 01:23:53 -0400777func (hs *serverHandshakeState) writeServerHash(msg []byte) {
778 // writeServerHash is called before writeRecord.
779 hs.writeHash(msg, hs.c.sendHandshakeSeq)
780}
781
782func (hs *serverHandshakeState) writeClientHash(msg []byte) {
783 // writeClientHash is called after readHandshake.
784 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
785}
786
787func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
788 if hs.c.isDTLS {
789 // This is somewhat hacky. DTLS hashes a slightly different format.
790 // First, the TLS header.
791 hs.finishedHash.Write(msg[:4])
792 // Then the sequence number and reassembled fragment offset (always 0).
793 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
794 // Then the reassembled fragment (always equal to the message length).
795 hs.finishedHash.Write(msg[1:4])
796 // And then the message body.
797 hs.finishedHash.Write(msg[4:])
798 } else {
799 hs.finishedHash.Write(msg)
800 }
801}
802
Adam Langley95c29f32014-06-20 12:00:00 -0700803// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
804// is acceptable to use.
805func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
806 for _, supported := range supportedCipherSuites {
807 if id == supported {
808 var candidate *cipherSuite
809
810 for _, s := range cipherSuites {
811 if s.id == id {
812 candidate = s
813 break
814 }
815 }
816 if candidate == nil {
817 continue
818 }
819 // Don't select a ciphersuite which we can't
820 // support for this client.
821 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
822 continue
823 }
824 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
825 continue
826 }
827 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
828 continue
829 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400830 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
831 continue
832 }
Adam Langley95c29f32014-06-20 12:00:00 -0700833 return candidate
834 }
835 }
836
837 return nil
838}