blob: 855f99255cdd488f071334e7b3826f19033d7061 [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 }
240
David Benjamind30a9902014-08-24 01:44:23 -0400241 if hs.clientHello.channelIDSupported && config.RequestChannelID {
242 hs.hello.channelIDRequested = true
243 }
244
Adam Langley95c29f32014-06-20 12:00:00 -0700245 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
246
247 if hs.checkForResumption() {
248 return true, nil
249 }
250
Adam Langleyac61fa32014-06-23 12:03:11 -0700251 var scsvFound bool
252
253 for _, cipherSuite := range hs.clientHello.cipherSuites {
254 if cipherSuite == fallbackSCSV {
255 scsvFound = true
256 break
257 }
258 }
259
260 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
261 return false, errors.New("tls: no fallback SCSV found when expected")
262 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
263 return false, errors.New("tls: fallback SCSV found when not expected")
264 }
265
Adam Langley95c29f32014-06-20 12:00:00 -0700266 var preferenceList, supportedList []uint16
267 if c.config.PreferServerCipherSuites {
268 preferenceList = c.config.cipherSuites()
269 supportedList = hs.clientHello.cipherSuites
270 } else {
271 preferenceList = hs.clientHello.cipherSuites
272 supportedList = c.config.cipherSuites()
273 }
274
275 for _, id := range preferenceList {
276 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
277 break
278 }
279 }
280
281 if hs.suite == nil {
282 c.sendAlert(alertHandshakeFailure)
283 return false, errors.New("tls: no cipher suite supported by both client and server")
284 }
285
286 return false, nil
287}
288
289// checkForResumption returns true if we should perform resumption on this connection.
290func (hs *serverHandshakeState) checkForResumption() bool {
291 c := hs.c
292
293 var ok bool
294 if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
295 return false
296 }
297
298 if hs.sessionState.vers > hs.clientHello.vers {
299 return false
300 }
301 if vers, ok := c.config.mutualVersion(hs.sessionState.vers); !ok || vers != hs.sessionState.vers {
302 return false
303 }
304
305 cipherSuiteOk := false
306 // Check that the client is still offering the ciphersuite in the session.
307 for _, id := range hs.clientHello.cipherSuites {
308 if id == hs.sessionState.cipherSuite {
309 cipherSuiteOk = true
310 break
311 }
312 }
313 if !cipherSuiteOk {
314 return false
315 }
316
317 // Check that we also support the ciphersuite from the session.
318 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk)
319 if hs.suite == nil {
320 return false
321 }
322
323 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
324 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
325 if needClientCerts && !sessionHasClientCerts {
326 return false
327 }
328 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
329 return false
330 }
331
332 return true
333}
334
335func (hs *serverHandshakeState) doResumeHandshake() error {
336 c := hs.c
337
338 hs.hello.cipherSuite = hs.suite.id
339 // We echo the client's session ID in the ServerHello to let it know
340 // that we're doing a resumption.
341 hs.hello.sessionId = hs.clientHello.sessionId
David Benjaminbed9aae2014-08-07 19:13:38 -0400342 hs.hello.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -0700343
344 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -0400345 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -0400346 hs.writeClientHash(hs.clientHello.marshal())
347 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700348
349 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
350
351 if len(hs.sessionState.certificates) > 0 {
352 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
353 return err
354 }
355 }
356
357 hs.masterSecret = hs.sessionState.masterSecret
358
359 return nil
360}
361
362func (hs *serverHandshakeState) doFullHandshake() error {
363 config := hs.c.config
364 c := hs.c
365
366 if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
367 hs.hello.ocspStapling = true
368 }
369
370 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled
371 hs.hello.cipherSuite = hs.suite.id
372
373 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400374 hs.writeClientHash(hs.clientHello.marshal())
375 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700376
377 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
378
379 certMsg := new(certificateMsg)
380 certMsg.certificates = hs.cert.Certificate
David Benjamin1c375dd2014-07-12 00:48:23 -0400381 if !config.Bugs.UnauthenticatedECDH {
David Benjamin83c0bc92014-08-04 01:23:53 -0400382 hs.writeServerHash(certMsg.marshal())
David Benjamin1c375dd2014-07-12 00:48:23 -0400383 c.writeRecord(recordTypeHandshake, certMsg.marshal())
384 }
Adam Langley95c29f32014-06-20 12:00:00 -0700385
386 if hs.hello.ocspStapling {
387 certStatus := new(certificateStatusMsg)
388 certStatus.statusType = statusTypeOCSP
389 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -0400390 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700391 c.writeRecord(recordTypeHandshake, certStatus.marshal())
392 }
393
394 keyAgreement := hs.suite.ka(c.vers)
395 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
396 if err != nil {
397 c.sendAlert(alertHandshakeFailure)
398 return err
399 }
David Benjamin9c651c92014-07-12 13:27:45 -0400400 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -0400401 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700402 c.writeRecord(recordTypeHandshake, skx.marshal())
403 }
404
405 if config.ClientAuth >= RequestClientCert {
406 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -0400407 certReq := &certificateRequestMsg{
408 certificateTypes: config.ClientCertificateTypes,
409 }
410 if certReq.certificateTypes == nil {
411 certReq.certificateTypes = []byte{
412 byte(CertTypeRSASign),
413 byte(CertTypeECDSASign),
414 }
Adam Langley95c29f32014-06-20 12:00:00 -0700415 }
416 if c.vers >= VersionTLS12 {
417 certReq.hasSignatureAndHash = true
418 certReq.signatureAndHashes = supportedClientCertSignatureAlgorithms
419 }
420
421 // An empty list of certificateAuthorities signals to
422 // the client that it may send any certificate in response
423 // to our request. When we know the CAs we trust, then
424 // we can send them down, so that the client can choose
425 // an appropriate certificate to give to us.
426 if config.ClientCAs != nil {
427 certReq.certificateAuthorities = config.ClientCAs.Subjects()
428 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400429 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700430 c.writeRecord(recordTypeHandshake, certReq.marshal())
431 }
432
433 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400434 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700435 c.writeRecord(recordTypeHandshake, helloDone.marshal())
436
437 var pub crypto.PublicKey // public key for client auth, if any
438
439 msg, err := c.readHandshake()
440 if err != nil {
441 return err
442 }
443
444 var ok bool
445 // If we requested a client certificate, then the client must send a
446 // certificate message, even if it's empty.
447 if config.ClientAuth >= RequestClientCert {
448 if certMsg, ok = msg.(*certificateMsg); !ok {
449 c.sendAlert(alertUnexpectedMessage)
450 return unexpectedMessageError(certMsg, msg)
451 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400452 hs.writeClientHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700453
454 if len(certMsg.certificates) == 0 {
455 // The client didn't actually send a certificate
456 switch config.ClientAuth {
457 case RequireAnyClientCert, RequireAndVerifyClientCert:
458 c.sendAlert(alertBadCertificate)
459 return errors.New("tls: client didn't provide a certificate")
460 }
461 }
462
463 pub, err = hs.processCertsFromClient(certMsg.certificates)
464 if err != nil {
465 return err
466 }
467
468 msg, err = c.readHandshake()
469 if err != nil {
470 return err
471 }
472 }
473
474 // Get client key exchange
475 ckx, ok := msg.(*clientKeyExchangeMsg)
476 if !ok {
477 c.sendAlert(alertUnexpectedMessage)
478 return unexpectedMessageError(ckx, msg)
479 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400480 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700481
David Benjamine098ec22014-08-27 23:13:20 -0400482 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
483 if err != nil {
484 c.sendAlert(alertHandshakeFailure)
485 return err
486 }
487 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
488
Adam Langley95c29f32014-06-20 12:00:00 -0700489 // If we received a client cert in response to our certificate request message,
490 // the client will send us a certificateVerifyMsg immediately after the
491 // clientKeyExchangeMsg. This message is a digest of all preceding
492 // handshake-layer messages that is signed using the private key corresponding
493 // to the client's certificate. This allows us to verify that the client is in
494 // possession of the private key of the certificate.
495 if len(c.peerCertificates) > 0 {
496 msg, err = c.readHandshake()
497 if err != nil {
498 return err
499 }
500 certVerify, ok := msg.(*certificateVerifyMsg)
501 if !ok {
502 c.sendAlert(alertUnexpectedMessage)
503 return unexpectedMessageError(certVerify, msg)
504 }
505
David Benjaminde620d92014-07-18 15:03:41 -0400506 // Determine the signature type.
507 var signatureAndHash signatureAndHash
508 if certVerify.hasSignatureAndHash {
509 signatureAndHash = certVerify.signatureAndHash
510 } else {
511 // Before TLS 1.2 the signature algorithm was implicit
512 // from the key type, and only one hash per signature
513 // algorithm was possible. Leave the hash as zero.
514 switch pub.(type) {
515 case *ecdsa.PublicKey:
516 signatureAndHash.signature = signatureECDSA
517 case *rsa.PublicKey:
518 signatureAndHash.signature = signatureRSA
519 }
520 }
521
Adam Langley95c29f32014-06-20 12:00:00 -0700522 switch key := pub.(type) {
523 case *ecdsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400524 if signatureAndHash.signature != signatureECDSA {
525 err = errors.New("tls: bad signature type for client's ECDSA certificate")
526 break
527 }
Adam Langley95c29f32014-06-20 12:00:00 -0700528 ecdsaSig := new(ecdsaSignature)
529 if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {
530 break
531 }
532 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
533 err = errors.New("ECDSA signature contained zero or negative values")
534 break
535 }
David Benjaminde620d92014-07-18 15:03:41 -0400536 var digest []byte
David Benjamine098ec22014-08-27 23:13:20 -0400537 digest, _, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400538 if err != nil {
539 break
540 }
Adam Langley95c29f32014-06-20 12:00:00 -0700541 if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {
542 err = errors.New("ECDSA verification failure")
543 break
544 }
545 case *rsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400546 if signatureAndHash.signature != signatureRSA {
547 err = errors.New("tls: bad signature type for client's RSA certificate")
548 break
549 }
550 var digest []byte
551 var hashFunc crypto.Hash
David Benjamine098ec22014-08-27 23:13:20 -0400552 digest, hashFunc, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400553 if err != nil {
554 break
555 }
Adam Langley95c29f32014-06-20 12:00:00 -0700556 err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)
557 }
558 if err != nil {
559 c.sendAlert(alertBadCertificate)
560 return errors.New("could not validate signature of connection nonces: " + err.Error())
561 }
562
David Benjamin83c0bc92014-08-04 01:23:53 -0400563 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700564 }
565
David Benjamine098ec22014-08-27 23:13:20 -0400566 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -0700567
568 return nil
569}
570
571func (hs *serverHandshakeState) establishKeys() error {
572 c := hs.c
573
574 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
575 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
576
577 var clientCipher, serverCipher interface{}
578 var clientHash, serverHash macFunction
579
580 if hs.suite.aead == nil {
581 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
582 clientHash = hs.suite.mac(c.vers, clientMAC)
583 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
584 serverHash = hs.suite.mac(c.vers, serverMAC)
585 } else {
586 clientCipher = hs.suite.aead(clientKey, clientIV)
587 serverCipher = hs.suite.aead(serverKey, serverIV)
588 }
589
590 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
591 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
592
593 return nil
594}
595
David Benjamind30a9902014-08-24 01:44:23 -0400596func (hs *serverHandshakeState) readFinished(isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700597 c := hs.c
598
599 c.readRecord(recordTypeChangeCipherSpec)
600 if err := c.in.error(); err != nil {
601 return err
602 }
603
604 if hs.hello.nextProtoNeg {
605 msg, err := c.readHandshake()
606 if err != nil {
607 return err
608 }
609 nextProto, ok := msg.(*nextProtoMsg)
610 if !ok {
611 c.sendAlert(alertUnexpectedMessage)
612 return unexpectedMessageError(nextProto, msg)
613 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400614 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700615 c.clientProtocol = nextProto.proto
616 }
617
David Benjamind30a9902014-08-24 01:44:23 -0400618 if hs.hello.channelIDRequested {
619 msg, err := c.readHandshake()
620 if err != nil {
621 return err
622 }
623 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
624 if !ok {
625 c.sendAlert(alertUnexpectedMessage)
626 return unexpectedMessageError(encryptedExtensions, msg)
627 }
628 x := new(big.Int).SetBytes(encryptedExtensions.channelID[0:32])
629 y := new(big.Int).SetBytes(encryptedExtensions.channelID[32:64])
630 r := new(big.Int).SetBytes(encryptedExtensions.channelID[64:96])
631 s := new(big.Int).SetBytes(encryptedExtensions.channelID[96:128])
632 if !elliptic.P256().IsOnCurve(x, y) {
633 return errors.New("tls: invalid channel ID public key")
634 }
635 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
636 var resumeHash []byte
637 if isResume {
638 resumeHash = hs.sessionState.handshakeHash
639 }
640 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
641 return errors.New("tls: invalid channel ID signature")
642 }
643 c.channelID = channelID
644
645 hs.writeClientHash(encryptedExtensions.marshal())
646 }
647
Adam Langley95c29f32014-06-20 12:00:00 -0700648 msg, err := c.readHandshake()
649 if err != nil {
650 return err
651 }
652 clientFinished, ok := msg.(*finishedMsg)
653 if !ok {
654 c.sendAlert(alertUnexpectedMessage)
655 return unexpectedMessageError(clientFinished, msg)
656 }
657
658 verify := hs.finishedHash.clientSum(hs.masterSecret)
659 if len(verify) != len(clientFinished.verifyData) ||
660 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
661 c.sendAlert(alertHandshakeFailure)
662 return errors.New("tls: client's Finished message is incorrect")
663 }
664
David Benjamin83c0bc92014-08-04 01:23:53 -0400665 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700666 return nil
667}
668
669func (hs *serverHandshakeState) sendSessionTicket() error {
David Benjamind23f4122014-07-23 15:09:48 -0400670 if !hs.hello.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
Adam Langley95c29f32014-06-20 12:00:00 -0700671 return nil
672 }
673
674 c := hs.c
675 m := new(newSessionTicketMsg)
676
677 var err error
678 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -0400679 vers: c.vers,
680 cipherSuite: hs.suite.id,
681 masterSecret: hs.masterSecret,
682 certificates: hs.certsFromClient,
683 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -0700684 }
685 m.ticket, err = c.encryptTicket(&state)
686 if err != nil {
687 return err
688 }
Adam Langley95c29f32014-06-20 12:00:00 -0700689
David Benjamin83c0bc92014-08-04 01:23:53 -0400690 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700691 c.writeRecord(recordTypeHandshake, m.marshal())
692
693 return nil
694}
695
696func (hs *serverHandshakeState) sendFinished() error {
697 c := hs.c
698
David Benjamin86271ee2014-07-21 16:14:03 -0400699 finished := new(finishedMsg)
700 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
701 postCCSBytes := finished.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -0400702 hs.writeServerHash(postCCSBytes)
David Benjamin86271ee2014-07-21 16:14:03 -0400703
704 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
705 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
706 postCCSBytes = postCCSBytes[5:]
707 }
708
David Benjamina0e52232014-07-19 17:39:58 -0400709 if !c.config.Bugs.SkipChangeCipherSpec {
710 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
711 }
Adam Langley95c29f32014-06-20 12:00:00 -0700712
David Benjamin86271ee2014-07-21 16:14:03 -0400713 c.writeRecord(recordTypeHandshake, postCCSBytes)
Adam Langley95c29f32014-06-20 12:00:00 -0700714
715 c.cipherSuite = hs.suite.id
716
717 return nil
718}
719
720// processCertsFromClient takes a chain of client certificates either from a
721// Certificates message or from a sessionState and verifies them. It returns
722// the public key of the leaf certificate.
723func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
724 c := hs.c
725
726 hs.certsFromClient = certificates
727 certs := make([]*x509.Certificate, len(certificates))
728 var err error
729 for i, asn1Data := range certificates {
730 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
731 c.sendAlert(alertBadCertificate)
732 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
733 }
734 }
735
736 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
737 opts := x509.VerifyOptions{
738 Roots: c.config.ClientCAs,
739 CurrentTime: c.config.time(),
740 Intermediates: x509.NewCertPool(),
741 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
742 }
743
744 for _, cert := range certs[1:] {
745 opts.Intermediates.AddCert(cert)
746 }
747
748 chains, err := certs[0].Verify(opts)
749 if err != nil {
750 c.sendAlert(alertBadCertificate)
751 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
752 }
753
754 ok := false
755 for _, ku := range certs[0].ExtKeyUsage {
756 if ku == x509.ExtKeyUsageClientAuth {
757 ok = true
758 break
759 }
760 }
761 if !ok {
762 c.sendAlert(alertHandshakeFailure)
763 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
764 }
765
766 c.verifiedChains = chains
767 }
768
769 if len(certs) > 0 {
770 var pub crypto.PublicKey
771 switch key := certs[0].PublicKey.(type) {
772 case *ecdsa.PublicKey, *rsa.PublicKey:
773 pub = key
774 default:
775 c.sendAlert(alertUnsupportedCertificate)
776 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
777 }
778 c.peerCertificates = certs
779 return pub, nil
780 }
781
782 return nil, nil
783}
784
David Benjamin83c0bc92014-08-04 01:23:53 -0400785func (hs *serverHandshakeState) writeServerHash(msg []byte) {
786 // writeServerHash is called before writeRecord.
787 hs.writeHash(msg, hs.c.sendHandshakeSeq)
788}
789
790func (hs *serverHandshakeState) writeClientHash(msg []byte) {
791 // writeClientHash is called after readHandshake.
792 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
793}
794
795func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
796 if hs.c.isDTLS {
797 // This is somewhat hacky. DTLS hashes a slightly different format.
798 // First, the TLS header.
799 hs.finishedHash.Write(msg[:4])
800 // Then the sequence number and reassembled fragment offset (always 0).
801 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
802 // Then the reassembled fragment (always equal to the message length).
803 hs.finishedHash.Write(msg[1:4])
804 // And then the message body.
805 hs.finishedHash.Write(msg[4:])
806 } else {
807 hs.finishedHash.Write(msg)
808 }
809}
810
Adam Langley95c29f32014-06-20 12:00:00 -0700811// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
812// is acceptable to use.
813func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
814 for _, supported := range supportedCipherSuites {
815 if id == supported {
816 var candidate *cipherSuite
817
818 for _, s := range cipherSuites {
819 if s.id == id {
820 candidate = s
821 break
822 }
823 }
824 if candidate == nil {
825 continue
826 }
827 // Don't select a ciphersuite which we can't
828 // support for this client.
829 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
830 continue
831 }
832 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
833 continue
834 }
835 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
836 continue
837 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400838 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
839 continue
840 }
Adam Langley95c29f32014-06-20 12:00:00 -0700841 return candidate
842 }
843 }
844
845 return nil
846}