blob: 72fa5029d04b4430c5d8ca5919da5a152d431fd7 [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 Benjamin83c0bc92014-08-04 01:23:53 -0400345 hs.writeClientHash(hs.clientHello.marshal())
346 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700347
348 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
349
350 if len(hs.sessionState.certificates) > 0 {
351 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
352 return err
353 }
354 }
355
356 hs.masterSecret = hs.sessionState.masterSecret
357
358 return nil
359}
360
361func (hs *serverHandshakeState) doFullHandshake() error {
362 config := hs.c.config
363 c := hs.c
364
365 if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
366 hs.hello.ocspStapling = true
367 }
368
369 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled
370 hs.hello.cipherSuite = hs.suite.id
371
372 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400373 hs.writeClientHash(hs.clientHello.marshal())
374 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700375
376 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
377
378 certMsg := new(certificateMsg)
379 certMsg.certificates = hs.cert.Certificate
David Benjamin1c375dd2014-07-12 00:48:23 -0400380 if !config.Bugs.UnauthenticatedECDH {
David Benjamin83c0bc92014-08-04 01:23:53 -0400381 hs.writeServerHash(certMsg.marshal())
David Benjamin1c375dd2014-07-12 00:48:23 -0400382 c.writeRecord(recordTypeHandshake, certMsg.marshal())
383 }
Adam Langley95c29f32014-06-20 12:00:00 -0700384
385 if hs.hello.ocspStapling {
386 certStatus := new(certificateStatusMsg)
387 certStatus.statusType = statusTypeOCSP
388 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -0400389 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700390 c.writeRecord(recordTypeHandshake, certStatus.marshal())
391 }
392
393 keyAgreement := hs.suite.ka(c.vers)
394 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
395 if err != nil {
396 c.sendAlert(alertHandshakeFailure)
397 return err
398 }
David Benjamin9c651c92014-07-12 13:27:45 -0400399 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -0400400 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700401 c.writeRecord(recordTypeHandshake, skx.marshal())
402 }
403
404 if config.ClientAuth >= RequestClientCert {
405 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -0400406 certReq := &certificateRequestMsg{
407 certificateTypes: config.ClientCertificateTypes,
408 }
409 if certReq.certificateTypes == nil {
410 certReq.certificateTypes = []byte{
411 byte(CertTypeRSASign),
412 byte(CertTypeECDSASign),
413 }
Adam Langley95c29f32014-06-20 12:00:00 -0700414 }
415 if c.vers >= VersionTLS12 {
416 certReq.hasSignatureAndHash = true
417 certReq.signatureAndHashes = supportedClientCertSignatureAlgorithms
418 }
419
420 // An empty list of certificateAuthorities signals to
421 // the client that it may send any certificate in response
422 // to our request. When we know the CAs we trust, then
423 // we can send them down, so that the client can choose
424 // an appropriate certificate to give to us.
425 if config.ClientCAs != nil {
426 certReq.certificateAuthorities = config.ClientCAs.Subjects()
427 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400428 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700429 c.writeRecord(recordTypeHandshake, certReq.marshal())
430 }
431
432 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400433 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700434 c.writeRecord(recordTypeHandshake, helloDone.marshal())
435
436 var pub crypto.PublicKey // public key for client auth, if any
437
438 msg, err := c.readHandshake()
439 if err != nil {
440 return err
441 }
442
443 var ok bool
444 // If we requested a client certificate, then the client must send a
445 // certificate message, even if it's empty.
446 if config.ClientAuth >= RequestClientCert {
447 if certMsg, ok = msg.(*certificateMsg); !ok {
448 c.sendAlert(alertUnexpectedMessage)
449 return unexpectedMessageError(certMsg, msg)
450 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400451 hs.writeClientHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700452
453 if len(certMsg.certificates) == 0 {
454 // The client didn't actually send a certificate
455 switch config.ClientAuth {
456 case RequireAnyClientCert, RequireAndVerifyClientCert:
457 c.sendAlert(alertBadCertificate)
458 return errors.New("tls: client didn't provide a certificate")
459 }
460 }
461
462 pub, err = hs.processCertsFromClient(certMsg.certificates)
463 if err != nil {
464 return err
465 }
466
467 msg, err = c.readHandshake()
468 if err != nil {
469 return err
470 }
471 }
472
473 // Get client key exchange
474 ckx, ok := msg.(*clientKeyExchangeMsg)
475 if !ok {
476 c.sendAlert(alertUnexpectedMessage)
477 return unexpectedMessageError(ckx, msg)
478 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400479 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700480
481 // If we received a client cert in response to our certificate request message,
482 // the client will send us a certificateVerifyMsg immediately after the
483 // clientKeyExchangeMsg. This message is a digest of all preceding
484 // handshake-layer messages that is signed using the private key corresponding
485 // to the client's certificate. This allows us to verify that the client is in
486 // possession of the private key of the certificate.
487 if len(c.peerCertificates) > 0 {
488 msg, err = c.readHandshake()
489 if err != nil {
490 return err
491 }
492 certVerify, ok := msg.(*certificateVerifyMsg)
493 if !ok {
494 c.sendAlert(alertUnexpectedMessage)
495 return unexpectedMessageError(certVerify, msg)
496 }
497
David Benjaminde620d92014-07-18 15:03:41 -0400498 // Determine the signature type.
499 var signatureAndHash signatureAndHash
500 if certVerify.hasSignatureAndHash {
501 signatureAndHash = certVerify.signatureAndHash
502 } else {
503 // Before TLS 1.2 the signature algorithm was implicit
504 // from the key type, and only one hash per signature
505 // algorithm was possible. Leave the hash as zero.
506 switch pub.(type) {
507 case *ecdsa.PublicKey:
508 signatureAndHash.signature = signatureECDSA
509 case *rsa.PublicKey:
510 signatureAndHash.signature = signatureRSA
511 }
512 }
513
Adam Langley95c29f32014-06-20 12:00:00 -0700514 switch key := pub.(type) {
515 case *ecdsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400516 if signatureAndHash.signature != signatureECDSA {
517 err = errors.New("tls: bad signature type for client's ECDSA certificate")
518 break
519 }
Adam Langley95c29f32014-06-20 12:00:00 -0700520 ecdsaSig := new(ecdsaSignature)
521 if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {
522 break
523 }
524 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
525 err = errors.New("ECDSA signature contained zero or negative values")
526 break
527 }
David Benjaminde620d92014-07-18 15:03:41 -0400528 var digest []byte
529 digest, _, err = hs.finishedHash.hashForClientCertificate(signatureAndHash)
530 if err != nil {
531 break
532 }
Adam Langley95c29f32014-06-20 12:00:00 -0700533 if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {
534 err = errors.New("ECDSA verification failure")
535 break
536 }
537 case *rsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400538 if signatureAndHash.signature != signatureRSA {
539 err = errors.New("tls: bad signature type for client's RSA certificate")
540 break
541 }
542 var digest []byte
543 var hashFunc crypto.Hash
544 digest, hashFunc, err = hs.finishedHash.hashForClientCertificate(signatureAndHash)
545 if err != nil {
546 break
547 }
Adam Langley95c29f32014-06-20 12:00:00 -0700548 err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)
549 }
550 if err != nil {
551 c.sendAlert(alertBadCertificate)
552 return errors.New("could not validate signature of connection nonces: " + err.Error())
553 }
554
David Benjamin83c0bc92014-08-04 01:23:53 -0400555 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700556 }
557
558 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
559 if err != nil {
560 c.sendAlert(alertHandshakeFailure)
561 return err
562 }
563 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
564
565 return nil
566}
567
568func (hs *serverHandshakeState) establishKeys() error {
569 c := hs.c
570
571 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
572 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
573
574 var clientCipher, serverCipher interface{}
575 var clientHash, serverHash macFunction
576
577 if hs.suite.aead == nil {
578 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
579 clientHash = hs.suite.mac(c.vers, clientMAC)
580 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
581 serverHash = hs.suite.mac(c.vers, serverMAC)
582 } else {
583 clientCipher = hs.suite.aead(clientKey, clientIV)
584 serverCipher = hs.suite.aead(serverKey, serverIV)
585 }
586
587 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
588 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
589
590 return nil
591}
592
David Benjamind30a9902014-08-24 01:44:23 -0400593func (hs *serverHandshakeState) readFinished(isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700594 c := hs.c
595
596 c.readRecord(recordTypeChangeCipherSpec)
597 if err := c.in.error(); err != nil {
598 return err
599 }
600
601 if hs.hello.nextProtoNeg {
602 msg, err := c.readHandshake()
603 if err != nil {
604 return err
605 }
606 nextProto, ok := msg.(*nextProtoMsg)
607 if !ok {
608 c.sendAlert(alertUnexpectedMessage)
609 return unexpectedMessageError(nextProto, msg)
610 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400611 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700612 c.clientProtocol = nextProto.proto
613 }
614
David Benjamind30a9902014-08-24 01:44:23 -0400615 if hs.hello.channelIDRequested {
616 msg, err := c.readHandshake()
617 if err != nil {
618 return err
619 }
620 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
621 if !ok {
622 c.sendAlert(alertUnexpectedMessage)
623 return unexpectedMessageError(encryptedExtensions, msg)
624 }
625 x := new(big.Int).SetBytes(encryptedExtensions.channelID[0:32])
626 y := new(big.Int).SetBytes(encryptedExtensions.channelID[32:64])
627 r := new(big.Int).SetBytes(encryptedExtensions.channelID[64:96])
628 s := new(big.Int).SetBytes(encryptedExtensions.channelID[96:128])
629 if !elliptic.P256().IsOnCurve(x, y) {
630 return errors.New("tls: invalid channel ID public key")
631 }
632 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
633 var resumeHash []byte
634 if isResume {
635 resumeHash = hs.sessionState.handshakeHash
636 }
637 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
638 return errors.New("tls: invalid channel ID signature")
639 }
640 c.channelID = channelID
641
642 hs.writeClientHash(encryptedExtensions.marshal())
643 }
644
Adam Langley95c29f32014-06-20 12:00:00 -0700645 msg, err := c.readHandshake()
646 if err != nil {
647 return err
648 }
649 clientFinished, ok := msg.(*finishedMsg)
650 if !ok {
651 c.sendAlert(alertUnexpectedMessage)
652 return unexpectedMessageError(clientFinished, msg)
653 }
654
655 verify := hs.finishedHash.clientSum(hs.masterSecret)
656 if len(verify) != len(clientFinished.verifyData) ||
657 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
658 c.sendAlert(alertHandshakeFailure)
659 return errors.New("tls: client's Finished message is incorrect")
660 }
661
David Benjamin83c0bc92014-08-04 01:23:53 -0400662 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700663 return nil
664}
665
666func (hs *serverHandshakeState) sendSessionTicket() error {
David Benjamind23f4122014-07-23 15:09:48 -0400667 if !hs.hello.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
Adam Langley95c29f32014-06-20 12:00:00 -0700668 return nil
669 }
670
671 c := hs.c
672 m := new(newSessionTicketMsg)
673
674 var err error
675 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -0400676 vers: c.vers,
677 cipherSuite: hs.suite.id,
678 masterSecret: hs.masterSecret,
679 certificates: hs.certsFromClient,
680 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -0700681 }
682 m.ticket, err = c.encryptTicket(&state)
683 if err != nil {
684 return err
685 }
Adam Langley95c29f32014-06-20 12:00:00 -0700686
David Benjamin83c0bc92014-08-04 01:23:53 -0400687 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700688 c.writeRecord(recordTypeHandshake, m.marshal())
689
690 return nil
691}
692
693func (hs *serverHandshakeState) sendFinished() error {
694 c := hs.c
695
David Benjamin86271ee2014-07-21 16:14:03 -0400696 finished := new(finishedMsg)
697 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
698 postCCSBytes := finished.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -0400699 hs.writeServerHash(postCCSBytes)
David Benjamin86271ee2014-07-21 16:14:03 -0400700
701 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
702 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
703 postCCSBytes = postCCSBytes[5:]
704 }
705
David Benjamina0e52232014-07-19 17:39:58 -0400706 if !c.config.Bugs.SkipChangeCipherSpec {
707 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
708 }
Adam Langley95c29f32014-06-20 12:00:00 -0700709
David Benjamin86271ee2014-07-21 16:14:03 -0400710 c.writeRecord(recordTypeHandshake, postCCSBytes)
Adam Langley95c29f32014-06-20 12:00:00 -0700711
712 c.cipherSuite = hs.suite.id
713
714 return nil
715}
716
717// processCertsFromClient takes a chain of client certificates either from a
718// Certificates message or from a sessionState and verifies them. It returns
719// the public key of the leaf certificate.
720func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
721 c := hs.c
722
723 hs.certsFromClient = certificates
724 certs := make([]*x509.Certificate, len(certificates))
725 var err error
726 for i, asn1Data := range certificates {
727 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
728 c.sendAlert(alertBadCertificate)
729 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
730 }
731 }
732
733 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
734 opts := x509.VerifyOptions{
735 Roots: c.config.ClientCAs,
736 CurrentTime: c.config.time(),
737 Intermediates: x509.NewCertPool(),
738 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
739 }
740
741 for _, cert := range certs[1:] {
742 opts.Intermediates.AddCert(cert)
743 }
744
745 chains, err := certs[0].Verify(opts)
746 if err != nil {
747 c.sendAlert(alertBadCertificate)
748 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
749 }
750
751 ok := false
752 for _, ku := range certs[0].ExtKeyUsage {
753 if ku == x509.ExtKeyUsageClientAuth {
754 ok = true
755 break
756 }
757 }
758 if !ok {
759 c.sendAlert(alertHandshakeFailure)
760 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
761 }
762
763 c.verifiedChains = chains
764 }
765
766 if len(certs) > 0 {
767 var pub crypto.PublicKey
768 switch key := certs[0].PublicKey.(type) {
769 case *ecdsa.PublicKey, *rsa.PublicKey:
770 pub = key
771 default:
772 c.sendAlert(alertUnsupportedCertificate)
773 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
774 }
775 c.peerCertificates = certs
776 return pub, nil
777 }
778
779 return nil, nil
780}
781
David Benjamin83c0bc92014-08-04 01:23:53 -0400782func (hs *serverHandshakeState) writeServerHash(msg []byte) {
783 // writeServerHash is called before writeRecord.
784 hs.writeHash(msg, hs.c.sendHandshakeSeq)
785}
786
787func (hs *serverHandshakeState) writeClientHash(msg []byte) {
788 // writeClientHash is called after readHandshake.
789 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
790}
791
792func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
793 if hs.c.isDTLS {
794 // This is somewhat hacky. DTLS hashes a slightly different format.
795 // First, the TLS header.
796 hs.finishedHash.Write(msg[:4])
797 // Then the sequence number and reassembled fragment offset (always 0).
798 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
799 // Then the reassembled fragment (always equal to the message length).
800 hs.finishedHash.Write(msg[1:4])
801 // And then the message body.
802 hs.finishedHash.Write(msg[4:])
803 } else {
804 hs.finishedHash.Write(msg)
805 }
806}
807
Adam Langley95c29f32014-06-20 12:00:00 -0700808// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
809// is acceptable to use.
810func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
811 for _, supported := range supportedCipherSuites {
812 if id == supported {
813 var candidate *cipherSuite
814
815 for _, s := range cipherSuites {
816 if s.id == id {
817 candidate = s
818 break
819 }
820 }
821 if candidate == nil {
822 continue
823 }
824 // Don't select a ciphersuite which we can't
825 // support for this client.
826 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
827 continue
828 }
829 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
830 continue
831 }
832 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
833 continue
834 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400835 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
836 continue
837 }
Adam Langley95c29f32014-06-20 12:00:00 -0700838 return candidate
839 }
840 }
841
842 return nil
843}