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