blob: 45e300d0792683d95483e2d05d3956d49883cfd0 [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 }
David Benjaminfa055a22014-09-15 16:51:51 -0400223
224 if len(hs.clientHello.alpnProtocols) > 0 {
225 if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
226 hs.hello.alpnProtocol = selectedProto
227 c.clientProtocol = selectedProto
David Benjaminfc7b0862014-09-06 13:21:53 -0400228 c.usedALPN = true
David Benjaminfa055a22014-09-15 16:51:51 -0400229 }
230 } else {
231 // Although sending an empty NPN extension is reasonable, Firefox has
232 // had a bug around this. Best to send nothing at all if
233 // config.NextProtos is empty. See
234 // https://code.google.com/p/go/issues/detail?id=5445.
235 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
236 hs.hello.nextProtoNeg = true
237 hs.hello.nextProtos = config.NextProtos
238 }
Adam Langley95c29f32014-06-20 12:00:00 -0700239 }
240
241 if len(config.Certificates) == 0 {
242 c.sendAlert(alertInternalError)
243 return false, errors.New("tls: no certificates configured")
244 }
245 hs.cert = &config.Certificates[0]
246 if len(hs.clientHello.serverName) > 0 {
247 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
248 }
David Benjamine78bfde2014-09-06 12:45:15 -0400249 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
250 return false, errors.New("tls: unexpected server name")
251 }
Adam Langley95c29f32014-06-20 12:00:00 -0700252
David Benjamind30a9902014-08-24 01:44:23 -0400253 if hs.clientHello.channelIDSupported && config.RequestChannelID {
254 hs.hello.channelIDRequested = true
255 }
256
Adam Langley95c29f32014-06-20 12:00:00 -0700257 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
258
259 if hs.checkForResumption() {
260 return true, nil
261 }
262
Adam Langleyac61fa32014-06-23 12:03:11 -0700263 var scsvFound bool
264
265 for _, cipherSuite := range hs.clientHello.cipherSuites {
266 if cipherSuite == fallbackSCSV {
267 scsvFound = true
268 break
269 }
270 }
271
272 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
273 return false, errors.New("tls: no fallback SCSV found when expected")
274 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
275 return false, errors.New("tls: fallback SCSV found when not expected")
276 }
277
Adam Langley95c29f32014-06-20 12:00:00 -0700278 var preferenceList, supportedList []uint16
279 if c.config.PreferServerCipherSuites {
280 preferenceList = c.config.cipherSuites()
281 supportedList = hs.clientHello.cipherSuites
282 } else {
283 preferenceList = hs.clientHello.cipherSuites
284 supportedList = c.config.cipherSuites()
285 }
286
287 for _, id := range preferenceList {
288 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
289 break
290 }
291 }
292
293 if hs.suite == nil {
294 c.sendAlert(alertHandshakeFailure)
295 return false, errors.New("tls: no cipher suite supported by both client and server")
296 }
297
298 return false, nil
299}
300
301// checkForResumption returns true if we should perform resumption on this connection.
302func (hs *serverHandshakeState) checkForResumption() bool {
303 c := hs.c
304
305 var ok bool
306 if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
307 return false
308 }
309
310 if hs.sessionState.vers > hs.clientHello.vers {
311 return false
312 }
313 if vers, ok := c.config.mutualVersion(hs.sessionState.vers); !ok || vers != hs.sessionState.vers {
314 return false
315 }
316
317 cipherSuiteOk := false
318 // Check that the client is still offering the ciphersuite in the session.
319 for _, id := range hs.clientHello.cipherSuites {
320 if id == hs.sessionState.cipherSuite {
321 cipherSuiteOk = true
322 break
323 }
324 }
325 if !cipherSuiteOk {
326 return false
327 }
328
329 // Check that we also support the ciphersuite from the session.
330 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk)
331 if hs.suite == nil {
332 return false
333 }
334
335 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
336 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
337 if needClientCerts && !sessionHasClientCerts {
338 return false
339 }
340 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
341 return false
342 }
343
344 return true
345}
346
347func (hs *serverHandshakeState) doResumeHandshake() error {
348 c := hs.c
349
350 hs.hello.cipherSuite = hs.suite.id
351 // We echo the client's session ID in the ServerHello to let it know
352 // that we're doing a resumption.
353 hs.hello.sessionId = hs.clientHello.sessionId
David Benjaminbed9aae2014-08-07 19:13:38 -0400354 hs.hello.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -0700355
356 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -0400357 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -0400358 hs.writeClientHash(hs.clientHello.marshal())
359 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700360
361 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
362
363 if len(hs.sessionState.certificates) > 0 {
364 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
365 return err
366 }
367 }
368
369 hs.masterSecret = hs.sessionState.masterSecret
370
371 return nil
372}
373
374func (hs *serverHandshakeState) doFullHandshake() error {
375 config := hs.c.config
376 c := hs.c
377
378 if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
379 hs.hello.ocspStapling = true
380 }
381
382 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled
383 hs.hello.cipherSuite = hs.suite.id
384
385 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400386 hs.writeClientHash(hs.clientHello.marshal())
387 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700388
389 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
390
391 certMsg := new(certificateMsg)
392 certMsg.certificates = hs.cert.Certificate
David Benjamin1c375dd2014-07-12 00:48:23 -0400393 if !config.Bugs.UnauthenticatedECDH {
David Benjamin83c0bc92014-08-04 01:23:53 -0400394 hs.writeServerHash(certMsg.marshal())
David Benjamin1c375dd2014-07-12 00:48:23 -0400395 c.writeRecord(recordTypeHandshake, certMsg.marshal())
396 }
Adam Langley95c29f32014-06-20 12:00:00 -0700397
398 if hs.hello.ocspStapling {
399 certStatus := new(certificateStatusMsg)
400 certStatus.statusType = statusTypeOCSP
401 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -0400402 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700403 c.writeRecord(recordTypeHandshake, certStatus.marshal())
404 }
405
406 keyAgreement := hs.suite.ka(c.vers)
407 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
408 if err != nil {
409 c.sendAlert(alertHandshakeFailure)
410 return err
411 }
David Benjamin9c651c92014-07-12 13:27:45 -0400412 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -0400413 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700414 c.writeRecord(recordTypeHandshake, skx.marshal())
415 }
416
417 if config.ClientAuth >= RequestClientCert {
418 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -0400419 certReq := &certificateRequestMsg{
420 certificateTypes: config.ClientCertificateTypes,
421 }
422 if certReq.certificateTypes == nil {
423 certReq.certificateTypes = []byte{
424 byte(CertTypeRSASign),
425 byte(CertTypeECDSASign),
426 }
Adam Langley95c29f32014-06-20 12:00:00 -0700427 }
428 if c.vers >= VersionTLS12 {
429 certReq.hasSignatureAndHash = true
430 certReq.signatureAndHashes = supportedClientCertSignatureAlgorithms
431 }
432
433 // An empty list of certificateAuthorities signals to
434 // the client that it may send any certificate in response
435 // to our request. When we know the CAs we trust, then
436 // we can send them down, so that the client can choose
437 // an appropriate certificate to give to us.
438 if config.ClientCAs != nil {
439 certReq.certificateAuthorities = config.ClientCAs.Subjects()
440 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400441 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700442 c.writeRecord(recordTypeHandshake, certReq.marshal())
443 }
444
445 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400446 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700447 c.writeRecord(recordTypeHandshake, helloDone.marshal())
448
449 var pub crypto.PublicKey // public key for client auth, if any
450
451 msg, err := c.readHandshake()
452 if err != nil {
453 return err
454 }
455
456 var ok bool
457 // If we requested a client certificate, then the client must send a
458 // certificate message, even if it's empty.
459 if config.ClientAuth >= RequestClientCert {
460 if certMsg, ok = msg.(*certificateMsg); !ok {
461 c.sendAlert(alertUnexpectedMessage)
462 return unexpectedMessageError(certMsg, msg)
463 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400464 hs.writeClientHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700465
466 if len(certMsg.certificates) == 0 {
467 // The client didn't actually send a certificate
468 switch config.ClientAuth {
469 case RequireAnyClientCert, RequireAndVerifyClientCert:
470 c.sendAlert(alertBadCertificate)
471 return errors.New("tls: client didn't provide a certificate")
472 }
473 }
474
475 pub, err = hs.processCertsFromClient(certMsg.certificates)
476 if err != nil {
477 return err
478 }
479
480 msg, err = c.readHandshake()
481 if err != nil {
482 return err
483 }
484 }
485
486 // Get client key exchange
487 ckx, ok := msg.(*clientKeyExchangeMsg)
488 if !ok {
489 c.sendAlert(alertUnexpectedMessage)
490 return unexpectedMessageError(ckx, msg)
491 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400492 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700493
David Benjamine098ec22014-08-27 23:13:20 -0400494 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
495 if err != nil {
496 c.sendAlert(alertHandshakeFailure)
497 return err
498 }
499 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
500
Adam Langley95c29f32014-06-20 12:00:00 -0700501 // If we received a client cert in response to our certificate request message,
502 // the client will send us a certificateVerifyMsg immediately after the
503 // clientKeyExchangeMsg. This message is a digest of all preceding
504 // handshake-layer messages that is signed using the private key corresponding
505 // to the client's certificate. This allows us to verify that the client is in
506 // possession of the private key of the certificate.
507 if len(c.peerCertificates) > 0 {
508 msg, err = c.readHandshake()
509 if err != nil {
510 return err
511 }
512 certVerify, ok := msg.(*certificateVerifyMsg)
513 if !ok {
514 c.sendAlert(alertUnexpectedMessage)
515 return unexpectedMessageError(certVerify, msg)
516 }
517
David Benjaminde620d92014-07-18 15:03:41 -0400518 // Determine the signature type.
519 var signatureAndHash signatureAndHash
520 if certVerify.hasSignatureAndHash {
521 signatureAndHash = certVerify.signatureAndHash
522 } else {
523 // Before TLS 1.2 the signature algorithm was implicit
524 // from the key type, and only one hash per signature
525 // algorithm was possible. Leave the hash as zero.
526 switch pub.(type) {
527 case *ecdsa.PublicKey:
528 signatureAndHash.signature = signatureECDSA
529 case *rsa.PublicKey:
530 signatureAndHash.signature = signatureRSA
531 }
532 }
533
Adam Langley95c29f32014-06-20 12:00:00 -0700534 switch key := pub.(type) {
535 case *ecdsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400536 if signatureAndHash.signature != signatureECDSA {
537 err = errors.New("tls: bad signature type for client's ECDSA certificate")
538 break
539 }
Adam Langley95c29f32014-06-20 12:00:00 -0700540 ecdsaSig := new(ecdsaSignature)
541 if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {
542 break
543 }
544 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
545 err = errors.New("ECDSA signature contained zero or negative values")
546 break
547 }
David Benjaminde620d92014-07-18 15:03:41 -0400548 var digest []byte
David Benjamine098ec22014-08-27 23:13:20 -0400549 digest, _, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400550 if err != nil {
551 break
552 }
Adam Langley95c29f32014-06-20 12:00:00 -0700553 if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {
554 err = errors.New("ECDSA verification failure")
555 break
556 }
557 case *rsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400558 if signatureAndHash.signature != signatureRSA {
559 err = errors.New("tls: bad signature type for client's RSA certificate")
560 break
561 }
562 var digest []byte
563 var hashFunc crypto.Hash
David Benjamine098ec22014-08-27 23:13:20 -0400564 digest, hashFunc, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400565 if err != nil {
566 break
567 }
Adam Langley95c29f32014-06-20 12:00:00 -0700568 err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)
569 }
570 if err != nil {
571 c.sendAlert(alertBadCertificate)
572 return errors.New("could not validate signature of connection nonces: " + err.Error())
573 }
574
David Benjamin83c0bc92014-08-04 01:23:53 -0400575 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700576 }
577
David Benjamine098ec22014-08-27 23:13:20 -0400578 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -0700579
580 return nil
581}
582
583func (hs *serverHandshakeState) establishKeys() error {
584 c := hs.c
585
586 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
587 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
588
589 var clientCipher, serverCipher interface{}
590 var clientHash, serverHash macFunction
591
592 if hs.suite.aead == nil {
593 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
594 clientHash = hs.suite.mac(c.vers, clientMAC)
595 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
596 serverHash = hs.suite.mac(c.vers, serverMAC)
597 } else {
598 clientCipher = hs.suite.aead(clientKey, clientIV)
599 serverCipher = hs.suite.aead(serverKey, serverIV)
600 }
601
602 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
603 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
604
605 return nil
606}
607
David Benjamind30a9902014-08-24 01:44:23 -0400608func (hs *serverHandshakeState) readFinished(isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700609 c := hs.c
610
611 c.readRecord(recordTypeChangeCipherSpec)
612 if err := c.in.error(); err != nil {
613 return err
614 }
615
616 if hs.hello.nextProtoNeg {
617 msg, err := c.readHandshake()
618 if err != nil {
619 return err
620 }
621 nextProto, ok := msg.(*nextProtoMsg)
622 if !ok {
623 c.sendAlert(alertUnexpectedMessage)
624 return unexpectedMessageError(nextProto, msg)
625 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400626 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700627 c.clientProtocol = nextProto.proto
628 }
629
David Benjamind30a9902014-08-24 01:44:23 -0400630 if hs.hello.channelIDRequested {
631 msg, err := c.readHandshake()
632 if err != nil {
633 return err
634 }
635 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
636 if !ok {
637 c.sendAlert(alertUnexpectedMessage)
638 return unexpectedMessageError(encryptedExtensions, msg)
639 }
640 x := new(big.Int).SetBytes(encryptedExtensions.channelID[0:32])
641 y := new(big.Int).SetBytes(encryptedExtensions.channelID[32:64])
642 r := new(big.Int).SetBytes(encryptedExtensions.channelID[64:96])
643 s := new(big.Int).SetBytes(encryptedExtensions.channelID[96:128])
644 if !elliptic.P256().IsOnCurve(x, y) {
645 return errors.New("tls: invalid channel ID public key")
646 }
647 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
648 var resumeHash []byte
649 if isResume {
650 resumeHash = hs.sessionState.handshakeHash
651 }
652 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
653 return errors.New("tls: invalid channel ID signature")
654 }
655 c.channelID = channelID
656
657 hs.writeClientHash(encryptedExtensions.marshal())
658 }
659
Adam Langley95c29f32014-06-20 12:00:00 -0700660 msg, err := c.readHandshake()
661 if err != nil {
662 return err
663 }
664 clientFinished, ok := msg.(*finishedMsg)
665 if !ok {
666 c.sendAlert(alertUnexpectedMessage)
667 return unexpectedMessageError(clientFinished, msg)
668 }
669
670 verify := hs.finishedHash.clientSum(hs.masterSecret)
671 if len(verify) != len(clientFinished.verifyData) ||
672 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
673 c.sendAlert(alertHandshakeFailure)
674 return errors.New("tls: client's Finished message is incorrect")
675 }
676
David Benjamin83c0bc92014-08-04 01:23:53 -0400677 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700678 return nil
679}
680
681func (hs *serverHandshakeState) sendSessionTicket() error {
David Benjamind23f4122014-07-23 15:09:48 -0400682 if !hs.hello.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
Adam Langley95c29f32014-06-20 12:00:00 -0700683 return nil
684 }
685
686 c := hs.c
687 m := new(newSessionTicketMsg)
688
689 var err error
690 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -0400691 vers: c.vers,
692 cipherSuite: hs.suite.id,
693 masterSecret: hs.masterSecret,
694 certificates: hs.certsFromClient,
695 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -0700696 }
697 m.ticket, err = c.encryptTicket(&state)
698 if err != nil {
699 return err
700 }
Adam Langley95c29f32014-06-20 12:00:00 -0700701
David Benjamin83c0bc92014-08-04 01:23:53 -0400702 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700703 c.writeRecord(recordTypeHandshake, m.marshal())
704
705 return nil
706}
707
708func (hs *serverHandshakeState) sendFinished() error {
709 c := hs.c
710
David Benjamin86271ee2014-07-21 16:14:03 -0400711 finished := new(finishedMsg)
712 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
713 postCCSBytes := finished.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -0400714 hs.writeServerHash(postCCSBytes)
David Benjamin86271ee2014-07-21 16:14:03 -0400715
716 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
717 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
718 postCCSBytes = postCCSBytes[5:]
719 }
720
David Benjamina0e52232014-07-19 17:39:58 -0400721 if !c.config.Bugs.SkipChangeCipherSpec {
722 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
723 }
Adam Langley95c29f32014-06-20 12:00:00 -0700724
David Benjamin86271ee2014-07-21 16:14:03 -0400725 c.writeRecord(recordTypeHandshake, postCCSBytes)
Adam Langley95c29f32014-06-20 12:00:00 -0700726
727 c.cipherSuite = hs.suite.id
728
729 return nil
730}
731
732// processCertsFromClient takes a chain of client certificates either from a
733// Certificates message or from a sessionState and verifies them. It returns
734// the public key of the leaf certificate.
735func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
736 c := hs.c
737
738 hs.certsFromClient = certificates
739 certs := make([]*x509.Certificate, len(certificates))
740 var err error
741 for i, asn1Data := range certificates {
742 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
743 c.sendAlert(alertBadCertificate)
744 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
745 }
746 }
747
748 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
749 opts := x509.VerifyOptions{
750 Roots: c.config.ClientCAs,
751 CurrentTime: c.config.time(),
752 Intermediates: x509.NewCertPool(),
753 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
754 }
755
756 for _, cert := range certs[1:] {
757 opts.Intermediates.AddCert(cert)
758 }
759
760 chains, err := certs[0].Verify(opts)
761 if err != nil {
762 c.sendAlert(alertBadCertificate)
763 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
764 }
765
766 ok := false
767 for _, ku := range certs[0].ExtKeyUsage {
768 if ku == x509.ExtKeyUsageClientAuth {
769 ok = true
770 break
771 }
772 }
773 if !ok {
774 c.sendAlert(alertHandshakeFailure)
775 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
776 }
777
778 c.verifiedChains = chains
779 }
780
781 if len(certs) > 0 {
782 var pub crypto.PublicKey
783 switch key := certs[0].PublicKey.(type) {
784 case *ecdsa.PublicKey, *rsa.PublicKey:
785 pub = key
786 default:
787 c.sendAlert(alertUnsupportedCertificate)
788 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
789 }
790 c.peerCertificates = certs
791 return pub, nil
792 }
793
794 return nil, nil
795}
796
David Benjamin83c0bc92014-08-04 01:23:53 -0400797func (hs *serverHandshakeState) writeServerHash(msg []byte) {
798 // writeServerHash is called before writeRecord.
799 hs.writeHash(msg, hs.c.sendHandshakeSeq)
800}
801
802func (hs *serverHandshakeState) writeClientHash(msg []byte) {
803 // writeClientHash is called after readHandshake.
804 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
805}
806
807func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
808 if hs.c.isDTLS {
809 // This is somewhat hacky. DTLS hashes a slightly different format.
810 // First, the TLS header.
811 hs.finishedHash.Write(msg[:4])
812 // Then the sequence number and reassembled fragment offset (always 0).
813 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
814 // Then the reassembled fragment (always equal to the message length).
815 hs.finishedHash.Write(msg[1:4])
816 // And then the message body.
817 hs.finishedHash.Write(msg[4:])
818 } else {
819 hs.finishedHash.Write(msg)
820 }
821}
822
Adam Langley95c29f32014-06-20 12:00:00 -0700823// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
824// is acceptable to use.
825func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
826 for _, supported := range supportedCipherSuites {
827 if id == supported {
828 var candidate *cipherSuite
829
830 for _, s := range cipherSuites {
831 if s.id == id {
832 candidate = s
833 break
834 }
835 }
836 if candidate == nil {
837 continue
838 }
839 // Don't select a ciphersuite which we can't
840 // support for this client.
841 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
842 continue
843 }
844 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
845 continue
846 }
David Benjamin39ebf532014-08-31 02:23:49 -0400847 if !c.config.Bugs.SkipCipherVersionCheck && version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700848 continue
849 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400850 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
851 continue
852 }
Adam Langley95c29f32014-06-20 12:00:00 -0700853 return candidate
854 }
855 }
856
857 return nil
858}