blob: b03f1654ee3011700a610099b0d093cac6063c16 [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
David Benjaminb0c8db72014-09-24 15:19:56 -0400305 if c.config.SessionTicketsDisabled {
306 return false
307 }
308
Adam Langley95c29f32014-06-20 12:00:00 -0700309 var ok bool
310 if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
311 return false
312 }
313
314 if hs.sessionState.vers > hs.clientHello.vers {
315 return false
316 }
317 if vers, ok := c.config.mutualVersion(hs.sessionState.vers); !ok || vers != hs.sessionState.vers {
318 return false
319 }
320
321 cipherSuiteOk := false
322 // Check that the client is still offering the ciphersuite in the session.
323 for _, id := range hs.clientHello.cipherSuites {
324 if id == hs.sessionState.cipherSuite {
325 cipherSuiteOk = true
326 break
327 }
328 }
329 if !cipherSuiteOk {
330 return false
331 }
332
333 // Check that we also support the ciphersuite from the session.
334 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk)
335 if hs.suite == nil {
336 return false
337 }
338
339 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
340 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
341 if needClientCerts && !sessionHasClientCerts {
342 return false
343 }
344 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
345 return false
346 }
347
348 return true
349}
350
351func (hs *serverHandshakeState) doResumeHandshake() error {
352 c := hs.c
353
354 hs.hello.cipherSuite = hs.suite.id
355 // We echo the client's session ID in the ServerHello to let it know
356 // that we're doing a resumption.
357 hs.hello.sessionId = hs.clientHello.sessionId
David Benjaminbed9aae2014-08-07 19:13:38 -0400358 hs.hello.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -0700359
360 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -0400361 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -0400362 hs.writeClientHash(hs.clientHello.marshal())
363 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700364
365 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
366
367 if len(hs.sessionState.certificates) > 0 {
368 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
369 return err
370 }
371 }
372
373 hs.masterSecret = hs.sessionState.masterSecret
374
375 return nil
376}
377
378func (hs *serverHandshakeState) doFullHandshake() error {
379 config := hs.c.config
380 c := hs.c
381
382 if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
383 hs.hello.ocspStapling = true
384 }
385
386 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled
387 hs.hello.cipherSuite = hs.suite.id
388
389 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400390 hs.writeClientHash(hs.clientHello.marshal())
391 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700392
393 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
394
395 certMsg := new(certificateMsg)
396 certMsg.certificates = hs.cert.Certificate
David Benjamin1c375dd2014-07-12 00:48:23 -0400397 if !config.Bugs.UnauthenticatedECDH {
David Benjamin83c0bc92014-08-04 01:23:53 -0400398 hs.writeServerHash(certMsg.marshal())
David Benjamin1c375dd2014-07-12 00:48:23 -0400399 c.writeRecord(recordTypeHandshake, certMsg.marshal())
400 }
Adam Langley95c29f32014-06-20 12:00:00 -0700401
402 if hs.hello.ocspStapling {
403 certStatus := new(certificateStatusMsg)
404 certStatus.statusType = statusTypeOCSP
405 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -0400406 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700407 c.writeRecord(recordTypeHandshake, certStatus.marshal())
408 }
409
410 keyAgreement := hs.suite.ka(c.vers)
411 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
412 if err != nil {
413 c.sendAlert(alertHandshakeFailure)
414 return err
415 }
David Benjamin9c651c92014-07-12 13:27:45 -0400416 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -0400417 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700418 c.writeRecord(recordTypeHandshake, skx.marshal())
419 }
420
421 if config.ClientAuth >= RequestClientCert {
422 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -0400423 certReq := &certificateRequestMsg{
424 certificateTypes: config.ClientCertificateTypes,
425 }
426 if certReq.certificateTypes == nil {
427 certReq.certificateTypes = []byte{
428 byte(CertTypeRSASign),
429 byte(CertTypeECDSASign),
430 }
Adam Langley95c29f32014-06-20 12:00:00 -0700431 }
432 if c.vers >= VersionTLS12 {
433 certReq.hasSignatureAndHash = true
434 certReq.signatureAndHashes = supportedClientCertSignatureAlgorithms
435 }
436
437 // An empty list of certificateAuthorities signals to
438 // the client that it may send any certificate in response
439 // to our request. When we know the CAs we trust, then
440 // we can send them down, so that the client can choose
441 // an appropriate certificate to give to us.
442 if config.ClientCAs != nil {
443 certReq.certificateAuthorities = config.ClientCAs.Subjects()
444 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400445 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700446 c.writeRecord(recordTypeHandshake, certReq.marshal())
447 }
448
449 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400450 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700451 c.writeRecord(recordTypeHandshake, helloDone.marshal())
452
453 var pub crypto.PublicKey // public key for client auth, if any
454
455 msg, err := c.readHandshake()
456 if err != nil {
457 return err
458 }
459
460 var ok bool
461 // If we requested a client certificate, then the client must send a
462 // certificate message, even if it's empty.
463 if config.ClientAuth >= RequestClientCert {
464 if certMsg, ok = msg.(*certificateMsg); !ok {
465 c.sendAlert(alertUnexpectedMessage)
466 return unexpectedMessageError(certMsg, msg)
467 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400468 hs.writeClientHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700469
470 if len(certMsg.certificates) == 0 {
471 // The client didn't actually send a certificate
472 switch config.ClientAuth {
473 case RequireAnyClientCert, RequireAndVerifyClientCert:
474 c.sendAlert(alertBadCertificate)
475 return errors.New("tls: client didn't provide a certificate")
476 }
477 }
478
479 pub, err = hs.processCertsFromClient(certMsg.certificates)
480 if err != nil {
481 return err
482 }
483
484 msg, err = c.readHandshake()
485 if err != nil {
486 return err
487 }
488 }
489
490 // Get client key exchange
491 ckx, ok := msg.(*clientKeyExchangeMsg)
492 if !ok {
493 c.sendAlert(alertUnexpectedMessage)
494 return unexpectedMessageError(ckx, msg)
495 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400496 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700497
David Benjamine098ec22014-08-27 23:13:20 -0400498 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
499 if err != nil {
500 c.sendAlert(alertHandshakeFailure)
501 return err
502 }
503 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
504
Adam Langley95c29f32014-06-20 12:00:00 -0700505 // If we received a client cert in response to our certificate request message,
506 // the client will send us a certificateVerifyMsg immediately after the
507 // clientKeyExchangeMsg. This message is a digest of all preceding
508 // handshake-layer messages that is signed using the private key corresponding
509 // to the client's certificate. This allows us to verify that the client is in
510 // possession of the private key of the certificate.
511 if len(c.peerCertificates) > 0 {
512 msg, err = c.readHandshake()
513 if err != nil {
514 return err
515 }
516 certVerify, ok := msg.(*certificateVerifyMsg)
517 if !ok {
518 c.sendAlert(alertUnexpectedMessage)
519 return unexpectedMessageError(certVerify, msg)
520 }
521
David Benjaminde620d92014-07-18 15:03:41 -0400522 // Determine the signature type.
523 var signatureAndHash signatureAndHash
524 if certVerify.hasSignatureAndHash {
525 signatureAndHash = certVerify.signatureAndHash
526 } else {
527 // Before TLS 1.2 the signature algorithm was implicit
528 // from the key type, and only one hash per signature
529 // algorithm was possible. Leave the hash as zero.
530 switch pub.(type) {
531 case *ecdsa.PublicKey:
532 signatureAndHash.signature = signatureECDSA
533 case *rsa.PublicKey:
534 signatureAndHash.signature = signatureRSA
535 }
536 }
537
Adam Langley95c29f32014-06-20 12:00:00 -0700538 switch key := pub.(type) {
539 case *ecdsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400540 if signatureAndHash.signature != signatureECDSA {
541 err = errors.New("tls: bad signature type for client's ECDSA certificate")
542 break
543 }
Adam Langley95c29f32014-06-20 12:00:00 -0700544 ecdsaSig := new(ecdsaSignature)
545 if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {
546 break
547 }
548 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
549 err = errors.New("ECDSA signature contained zero or negative values")
550 break
551 }
David Benjaminde620d92014-07-18 15:03:41 -0400552 var digest []byte
David Benjamine098ec22014-08-27 23:13:20 -0400553 digest, _, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400554 if err != nil {
555 break
556 }
Adam Langley95c29f32014-06-20 12:00:00 -0700557 if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {
558 err = errors.New("ECDSA verification failure")
559 break
560 }
561 case *rsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400562 if signatureAndHash.signature != signatureRSA {
563 err = errors.New("tls: bad signature type for client's RSA certificate")
564 break
565 }
566 var digest []byte
567 var hashFunc crypto.Hash
David Benjamine098ec22014-08-27 23:13:20 -0400568 digest, hashFunc, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400569 if err != nil {
570 break
571 }
Adam Langley95c29f32014-06-20 12:00:00 -0700572 err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)
573 }
574 if err != nil {
575 c.sendAlert(alertBadCertificate)
576 return errors.New("could not validate signature of connection nonces: " + err.Error())
577 }
578
David Benjamin83c0bc92014-08-04 01:23:53 -0400579 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700580 }
581
David Benjamine098ec22014-08-27 23:13:20 -0400582 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -0700583
584 return nil
585}
586
587func (hs *serverHandshakeState) establishKeys() error {
588 c := hs.c
589
590 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
591 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
592
593 var clientCipher, serverCipher interface{}
594 var clientHash, serverHash macFunction
595
596 if hs.suite.aead == nil {
597 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
598 clientHash = hs.suite.mac(c.vers, clientMAC)
599 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
600 serverHash = hs.suite.mac(c.vers, serverMAC)
601 } else {
602 clientCipher = hs.suite.aead(clientKey, clientIV)
603 serverCipher = hs.suite.aead(serverKey, serverIV)
604 }
605
606 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
607 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
608
609 return nil
610}
611
David Benjamind30a9902014-08-24 01:44:23 -0400612func (hs *serverHandshakeState) readFinished(isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700613 c := hs.c
614
615 c.readRecord(recordTypeChangeCipherSpec)
616 if err := c.in.error(); err != nil {
617 return err
618 }
619
620 if hs.hello.nextProtoNeg {
621 msg, err := c.readHandshake()
622 if err != nil {
623 return err
624 }
625 nextProto, ok := msg.(*nextProtoMsg)
626 if !ok {
627 c.sendAlert(alertUnexpectedMessage)
628 return unexpectedMessageError(nextProto, msg)
629 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400630 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700631 c.clientProtocol = nextProto.proto
632 }
633
David Benjamind30a9902014-08-24 01:44:23 -0400634 if hs.hello.channelIDRequested {
635 msg, err := c.readHandshake()
636 if err != nil {
637 return err
638 }
639 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
640 if !ok {
641 c.sendAlert(alertUnexpectedMessage)
642 return unexpectedMessageError(encryptedExtensions, msg)
643 }
644 x := new(big.Int).SetBytes(encryptedExtensions.channelID[0:32])
645 y := new(big.Int).SetBytes(encryptedExtensions.channelID[32:64])
646 r := new(big.Int).SetBytes(encryptedExtensions.channelID[64:96])
647 s := new(big.Int).SetBytes(encryptedExtensions.channelID[96:128])
648 if !elliptic.P256().IsOnCurve(x, y) {
649 return errors.New("tls: invalid channel ID public key")
650 }
651 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
652 var resumeHash []byte
653 if isResume {
654 resumeHash = hs.sessionState.handshakeHash
655 }
656 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
657 return errors.New("tls: invalid channel ID signature")
658 }
659 c.channelID = channelID
660
661 hs.writeClientHash(encryptedExtensions.marshal())
662 }
663
Adam Langley95c29f32014-06-20 12:00:00 -0700664 msg, err := c.readHandshake()
665 if err != nil {
666 return err
667 }
668 clientFinished, ok := msg.(*finishedMsg)
669 if !ok {
670 c.sendAlert(alertUnexpectedMessage)
671 return unexpectedMessageError(clientFinished, msg)
672 }
673
674 verify := hs.finishedHash.clientSum(hs.masterSecret)
675 if len(verify) != len(clientFinished.verifyData) ||
676 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
677 c.sendAlert(alertHandshakeFailure)
678 return errors.New("tls: client's Finished message is incorrect")
679 }
680
David Benjamin83c0bc92014-08-04 01:23:53 -0400681 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700682 return nil
683}
684
685func (hs *serverHandshakeState) sendSessionTicket() error {
David Benjamind23f4122014-07-23 15:09:48 -0400686 if !hs.hello.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
Adam Langley95c29f32014-06-20 12:00:00 -0700687 return nil
688 }
689
690 c := hs.c
691 m := new(newSessionTicketMsg)
692
693 var err error
694 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -0400695 vers: c.vers,
696 cipherSuite: hs.suite.id,
697 masterSecret: hs.masterSecret,
698 certificates: hs.certsFromClient,
699 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -0700700 }
701 m.ticket, err = c.encryptTicket(&state)
702 if err != nil {
703 return err
704 }
Adam Langley95c29f32014-06-20 12:00:00 -0700705
David Benjamin83c0bc92014-08-04 01:23:53 -0400706 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700707 c.writeRecord(recordTypeHandshake, m.marshal())
708
709 return nil
710}
711
712func (hs *serverHandshakeState) sendFinished() error {
713 c := hs.c
714
David Benjamin86271ee2014-07-21 16:14:03 -0400715 finished := new(finishedMsg)
716 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
717 postCCSBytes := finished.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -0400718 hs.writeServerHash(postCCSBytes)
David Benjamin86271ee2014-07-21 16:14:03 -0400719
720 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
721 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
722 postCCSBytes = postCCSBytes[5:]
723 }
724
David Benjamina0e52232014-07-19 17:39:58 -0400725 if !c.config.Bugs.SkipChangeCipherSpec {
726 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
727 }
Adam Langley95c29f32014-06-20 12:00:00 -0700728
David Benjamin86271ee2014-07-21 16:14:03 -0400729 c.writeRecord(recordTypeHandshake, postCCSBytes)
Adam Langley95c29f32014-06-20 12:00:00 -0700730
731 c.cipherSuite = hs.suite.id
732
733 return nil
734}
735
736// processCertsFromClient takes a chain of client certificates either from a
737// Certificates message or from a sessionState and verifies them. It returns
738// the public key of the leaf certificate.
739func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
740 c := hs.c
741
742 hs.certsFromClient = certificates
743 certs := make([]*x509.Certificate, len(certificates))
744 var err error
745 for i, asn1Data := range certificates {
746 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
747 c.sendAlert(alertBadCertificate)
748 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
749 }
750 }
751
752 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
753 opts := x509.VerifyOptions{
754 Roots: c.config.ClientCAs,
755 CurrentTime: c.config.time(),
756 Intermediates: x509.NewCertPool(),
757 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
758 }
759
760 for _, cert := range certs[1:] {
761 opts.Intermediates.AddCert(cert)
762 }
763
764 chains, err := certs[0].Verify(opts)
765 if err != nil {
766 c.sendAlert(alertBadCertificate)
767 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
768 }
769
770 ok := false
771 for _, ku := range certs[0].ExtKeyUsage {
772 if ku == x509.ExtKeyUsageClientAuth {
773 ok = true
774 break
775 }
776 }
777 if !ok {
778 c.sendAlert(alertHandshakeFailure)
779 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
780 }
781
782 c.verifiedChains = chains
783 }
784
785 if len(certs) > 0 {
786 var pub crypto.PublicKey
787 switch key := certs[0].PublicKey.(type) {
788 case *ecdsa.PublicKey, *rsa.PublicKey:
789 pub = key
790 default:
791 c.sendAlert(alertUnsupportedCertificate)
792 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
793 }
794 c.peerCertificates = certs
795 return pub, nil
796 }
797
798 return nil, nil
799}
800
David Benjamin83c0bc92014-08-04 01:23:53 -0400801func (hs *serverHandshakeState) writeServerHash(msg []byte) {
802 // writeServerHash is called before writeRecord.
803 hs.writeHash(msg, hs.c.sendHandshakeSeq)
804}
805
806func (hs *serverHandshakeState) writeClientHash(msg []byte) {
807 // writeClientHash is called after readHandshake.
808 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
809}
810
811func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
812 if hs.c.isDTLS {
813 // This is somewhat hacky. DTLS hashes a slightly different format.
814 // First, the TLS header.
815 hs.finishedHash.Write(msg[:4])
816 // Then the sequence number and reassembled fragment offset (always 0).
817 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
818 // Then the reassembled fragment (always equal to the message length).
819 hs.finishedHash.Write(msg[1:4])
820 // And then the message body.
821 hs.finishedHash.Write(msg[4:])
822 } else {
823 hs.finishedHash.Write(msg)
824 }
825}
826
Adam Langley95c29f32014-06-20 12:00:00 -0700827// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
828// is acceptable to use.
829func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
830 for _, supported := range supportedCipherSuites {
831 if id == supported {
832 var candidate *cipherSuite
833
834 for _, s := range cipherSuites {
835 if s.id == id {
836 candidate = s
837 break
838 }
839 }
840 if candidate == nil {
841 continue
842 }
843 // Don't select a ciphersuite which we can't
844 // support for this client.
845 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
846 continue
847 }
848 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
849 continue
850 }
David Benjamin39ebf532014-08-31 02:23:49 -0400851 if !c.config.Bugs.SkipCipherVersionCheck && version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700852 continue
853 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400854 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
855 continue
856 }
Adam Langley95c29f32014-06-20 12:00:00 -0700857 return candidate
858 }
859 }
860
861 return nil
862}