blob: 645a67c00a65fd0fc18b928c1128a0d088d7cb33 [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 }
Adam Langley75712922014-10-10 16:23:43 -0700240 hs.hello.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !c.config.Bugs.NoExtendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700241
242 if len(config.Certificates) == 0 {
243 c.sendAlert(alertInternalError)
244 return false, errors.New("tls: no certificates configured")
245 }
246 hs.cert = &config.Certificates[0]
247 if len(hs.clientHello.serverName) > 0 {
248 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
249 }
David Benjamine78bfde2014-09-06 12:45:15 -0400250 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
251 return false, errors.New("tls: unexpected server name")
252 }
Adam Langley95c29f32014-06-20 12:00:00 -0700253
David Benjamind30a9902014-08-24 01:44:23 -0400254 if hs.clientHello.channelIDSupported && config.RequestChannelID {
255 hs.hello.channelIDRequested = true
256 }
257
Adam Langley95c29f32014-06-20 12:00:00 -0700258 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
259
260 if hs.checkForResumption() {
261 return true, nil
262 }
263
Adam Langleyac61fa32014-06-23 12:03:11 -0700264 var scsvFound bool
265
266 for _, cipherSuite := range hs.clientHello.cipherSuites {
267 if cipherSuite == fallbackSCSV {
268 scsvFound = true
269 break
270 }
271 }
272
273 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
274 return false, errors.New("tls: no fallback SCSV found when expected")
275 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
276 return false, errors.New("tls: fallback SCSV found when not expected")
277 }
278
Adam Langley95c29f32014-06-20 12:00:00 -0700279 var preferenceList, supportedList []uint16
280 if c.config.PreferServerCipherSuites {
281 preferenceList = c.config.cipherSuites()
282 supportedList = hs.clientHello.cipherSuites
283 } else {
284 preferenceList = hs.clientHello.cipherSuites
285 supportedList = c.config.cipherSuites()
286 }
287
288 for _, id := range preferenceList {
289 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
290 break
291 }
292 }
293
294 if hs.suite == nil {
295 c.sendAlert(alertHandshakeFailure)
296 return false, errors.New("tls: no cipher suite supported by both client and server")
297 }
298
299 return false, nil
300}
301
302// checkForResumption returns true if we should perform resumption on this connection.
303func (hs *serverHandshakeState) checkForResumption() bool {
304 c := hs.c
305
David Benjaminb0c8db72014-09-24 15:19:56 -0400306 if c.config.SessionTicketsDisabled {
307 return false
308 }
309
Adam Langley95c29f32014-06-20 12:00:00 -0700310 var ok bool
311 if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
312 return false
313 }
314
David Benjamin01fe8202014-09-24 15:21:44 -0400315 if !c.config.Bugs.AllowSessionVersionMismatch {
316 if hs.sessionState.vers > hs.clientHello.vers {
317 return false
318 }
319 if vers, ok := c.config.mutualVersion(hs.sessionState.vers); !ok || vers != hs.sessionState.vers {
320 return false
321 }
Adam Langley95c29f32014-06-20 12:00:00 -0700322 }
323
324 cipherSuiteOk := false
325 // Check that the client is still offering the ciphersuite in the session.
326 for _, id := range hs.clientHello.cipherSuites {
327 if id == hs.sessionState.cipherSuite {
328 cipherSuiteOk = true
329 break
330 }
331 }
332 if !cipherSuiteOk {
333 return false
334 }
335
336 // Check that we also support the ciphersuite from the session.
337 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk)
338 if hs.suite == nil {
339 return false
340 }
341
342 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
343 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
344 if needClientCerts && !sessionHasClientCerts {
345 return false
346 }
347 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
348 return false
349 }
350
351 return true
352}
353
354func (hs *serverHandshakeState) doResumeHandshake() error {
355 c := hs.c
356
357 hs.hello.cipherSuite = hs.suite.id
358 // We echo the client's session ID in the ServerHello to let it know
359 // that we're doing a resumption.
360 hs.hello.sessionId = hs.clientHello.sessionId
David Benjaminbed9aae2014-08-07 19:13:38 -0400361 hs.hello.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -0700362
363 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -0400364 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -0400365 hs.writeClientHash(hs.clientHello.marshal())
366 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700367
368 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
369
370 if len(hs.sessionState.certificates) > 0 {
371 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
372 return err
373 }
374 }
375
376 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -0700377 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700378
379 return nil
380}
381
382func (hs *serverHandshakeState) doFullHandshake() error {
383 config := hs.c.config
384 c := hs.c
385
386 if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
387 hs.hello.ocspStapling = true
388 }
389
390 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled
391 hs.hello.cipherSuite = hs.suite.id
Adam Langley75712922014-10-10 16:23:43 -0700392 c.extendedMasterSecret = hs.hello.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700393
394 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400395 hs.writeClientHash(hs.clientHello.marshal())
396 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700397
398 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
399
400 certMsg := new(certificateMsg)
401 certMsg.certificates = hs.cert.Certificate
David Benjamin1c375dd2014-07-12 00:48:23 -0400402 if !config.Bugs.UnauthenticatedECDH {
David Benjamin83c0bc92014-08-04 01:23:53 -0400403 hs.writeServerHash(certMsg.marshal())
David Benjamin1c375dd2014-07-12 00:48:23 -0400404 c.writeRecord(recordTypeHandshake, certMsg.marshal())
405 }
Adam Langley95c29f32014-06-20 12:00:00 -0700406
407 if hs.hello.ocspStapling {
408 certStatus := new(certificateStatusMsg)
409 certStatus.statusType = statusTypeOCSP
410 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -0400411 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700412 c.writeRecord(recordTypeHandshake, certStatus.marshal())
413 }
414
415 keyAgreement := hs.suite.ka(c.vers)
416 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
417 if err != nil {
418 c.sendAlert(alertHandshakeFailure)
419 return err
420 }
David Benjamin9c651c92014-07-12 13:27:45 -0400421 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -0400422 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700423 c.writeRecord(recordTypeHandshake, skx.marshal())
424 }
425
426 if config.ClientAuth >= RequestClientCert {
427 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -0400428 certReq := &certificateRequestMsg{
429 certificateTypes: config.ClientCertificateTypes,
430 }
431 if certReq.certificateTypes == nil {
432 certReq.certificateTypes = []byte{
433 byte(CertTypeRSASign),
434 byte(CertTypeECDSASign),
435 }
Adam Langley95c29f32014-06-20 12:00:00 -0700436 }
437 if c.vers >= VersionTLS12 {
438 certReq.hasSignatureAndHash = true
439 certReq.signatureAndHashes = supportedClientCertSignatureAlgorithms
440 }
441
442 // An empty list of certificateAuthorities signals to
443 // the client that it may send any certificate in response
444 // to our request. When we know the CAs we trust, then
445 // we can send them down, so that the client can choose
446 // an appropriate certificate to give to us.
447 if config.ClientCAs != nil {
448 certReq.certificateAuthorities = config.ClientCAs.Subjects()
449 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400450 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700451 c.writeRecord(recordTypeHandshake, certReq.marshal())
452 }
453
454 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400455 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700456 c.writeRecord(recordTypeHandshake, helloDone.marshal())
457
458 var pub crypto.PublicKey // public key for client auth, if any
459
460 msg, err := c.readHandshake()
461 if err != nil {
462 return err
463 }
464
465 var ok bool
466 // If we requested a client certificate, then the client must send a
467 // certificate message, even if it's empty.
468 if config.ClientAuth >= RequestClientCert {
469 if certMsg, ok = msg.(*certificateMsg); !ok {
470 c.sendAlert(alertUnexpectedMessage)
471 return unexpectedMessageError(certMsg, msg)
472 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400473 hs.writeClientHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700474
475 if len(certMsg.certificates) == 0 {
476 // The client didn't actually send a certificate
477 switch config.ClientAuth {
478 case RequireAnyClientCert, RequireAndVerifyClientCert:
479 c.sendAlert(alertBadCertificate)
480 return errors.New("tls: client didn't provide a certificate")
481 }
482 }
483
484 pub, err = hs.processCertsFromClient(certMsg.certificates)
485 if err != nil {
486 return err
487 }
488
489 msg, err = c.readHandshake()
490 if err != nil {
491 return err
492 }
493 }
494
495 // Get client key exchange
496 ckx, ok := msg.(*clientKeyExchangeMsg)
497 if !ok {
498 c.sendAlert(alertUnexpectedMessage)
499 return unexpectedMessageError(ckx, msg)
500 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400501 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700502
David Benjamine098ec22014-08-27 23:13:20 -0400503 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
504 if err != nil {
505 c.sendAlert(alertHandshakeFailure)
506 return err
507 }
Adam Langley75712922014-10-10 16:23:43 -0700508 if c.extendedMasterSecret {
509 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
510 } else {
511 if c.config.Bugs.RequireExtendedMasterSecret {
512 return errors.New("tls: extended master secret required but not supported by peer")
513 }
514 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
515 }
David Benjamine098ec22014-08-27 23:13:20 -0400516
Adam Langley95c29f32014-06-20 12:00:00 -0700517 // If we received a client cert in response to our certificate request message,
518 // the client will send us a certificateVerifyMsg immediately after the
519 // clientKeyExchangeMsg. This message is a digest of all preceding
520 // handshake-layer messages that is signed using the private key corresponding
521 // to the client's certificate. This allows us to verify that the client is in
522 // possession of the private key of the certificate.
523 if len(c.peerCertificates) > 0 {
524 msg, err = c.readHandshake()
525 if err != nil {
526 return err
527 }
528 certVerify, ok := msg.(*certificateVerifyMsg)
529 if !ok {
530 c.sendAlert(alertUnexpectedMessage)
531 return unexpectedMessageError(certVerify, msg)
532 }
533
David Benjaminde620d92014-07-18 15:03:41 -0400534 // Determine the signature type.
535 var signatureAndHash signatureAndHash
536 if certVerify.hasSignatureAndHash {
537 signatureAndHash = certVerify.signatureAndHash
538 } else {
539 // Before TLS 1.2 the signature algorithm was implicit
540 // from the key type, and only one hash per signature
541 // algorithm was possible. Leave the hash as zero.
542 switch pub.(type) {
543 case *ecdsa.PublicKey:
544 signatureAndHash.signature = signatureECDSA
545 case *rsa.PublicKey:
546 signatureAndHash.signature = signatureRSA
547 }
548 }
549
Adam Langley95c29f32014-06-20 12:00:00 -0700550 switch key := pub.(type) {
551 case *ecdsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400552 if signatureAndHash.signature != signatureECDSA {
553 err = errors.New("tls: bad signature type for client's ECDSA certificate")
554 break
555 }
Adam Langley95c29f32014-06-20 12:00:00 -0700556 ecdsaSig := new(ecdsaSignature)
557 if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {
558 break
559 }
560 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
561 err = errors.New("ECDSA signature contained zero or negative values")
562 break
563 }
David Benjaminde620d92014-07-18 15:03:41 -0400564 var digest []byte
David Benjamine098ec22014-08-27 23:13:20 -0400565 digest, _, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400566 if err != nil {
567 break
568 }
Adam Langley95c29f32014-06-20 12:00:00 -0700569 if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {
570 err = errors.New("ECDSA verification failure")
571 break
572 }
573 case *rsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400574 if signatureAndHash.signature != signatureRSA {
575 err = errors.New("tls: bad signature type for client's RSA certificate")
576 break
577 }
578 var digest []byte
579 var hashFunc crypto.Hash
David Benjamine098ec22014-08-27 23:13:20 -0400580 digest, hashFunc, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400581 if err != nil {
582 break
583 }
Adam Langley95c29f32014-06-20 12:00:00 -0700584 err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)
585 }
586 if err != nil {
587 c.sendAlert(alertBadCertificate)
588 return errors.New("could not validate signature of connection nonces: " + err.Error())
589 }
590
David Benjamin83c0bc92014-08-04 01:23:53 -0400591 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700592 }
593
David Benjamine098ec22014-08-27 23:13:20 -0400594 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -0700595
596 return nil
597}
598
599func (hs *serverHandshakeState) establishKeys() error {
600 c := hs.c
601
602 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
603 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
604
605 var clientCipher, serverCipher interface{}
606 var clientHash, serverHash macFunction
607
608 if hs.suite.aead == nil {
609 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
610 clientHash = hs.suite.mac(c.vers, clientMAC)
611 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
612 serverHash = hs.suite.mac(c.vers, serverMAC)
613 } else {
614 clientCipher = hs.suite.aead(clientKey, clientIV)
615 serverCipher = hs.suite.aead(serverKey, serverIV)
616 }
617
618 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
619 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
620
621 return nil
622}
623
David Benjamind30a9902014-08-24 01:44:23 -0400624func (hs *serverHandshakeState) readFinished(isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700625 c := hs.c
626
627 c.readRecord(recordTypeChangeCipherSpec)
628 if err := c.in.error(); err != nil {
629 return err
630 }
631
632 if hs.hello.nextProtoNeg {
633 msg, err := c.readHandshake()
634 if err != nil {
635 return err
636 }
637 nextProto, ok := msg.(*nextProtoMsg)
638 if !ok {
639 c.sendAlert(alertUnexpectedMessage)
640 return unexpectedMessageError(nextProto, msg)
641 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400642 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700643 c.clientProtocol = nextProto.proto
644 }
645
David Benjamind30a9902014-08-24 01:44:23 -0400646 if hs.hello.channelIDRequested {
647 msg, err := c.readHandshake()
648 if err != nil {
649 return err
650 }
651 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
652 if !ok {
653 c.sendAlert(alertUnexpectedMessage)
654 return unexpectedMessageError(encryptedExtensions, msg)
655 }
656 x := new(big.Int).SetBytes(encryptedExtensions.channelID[0:32])
657 y := new(big.Int).SetBytes(encryptedExtensions.channelID[32:64])
658 r := new(big.Int).SetBytes(encryptedExtensions.channelID[64:96])
659 s := new(big.Int).SetBytes(encryptedExtensions.channelID[96:128])
660 if !elliptic.P256().IsOnCurve(x, y) {
661 return errors.New("tls: invalid channel ID public key")
662 }
663 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
664 var resumeHash []byte
665 if isResume {
666 resumeHash = hs.sessionState.handshakeHash
667 }
668 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
669 return errors.New("tls: invalid channel ID signature")
670 }
671 c.channelID = channelID
672
673 hs.writeClientHash(encryptedExtensions.marshal())
674 }
675
Adam Langley95c29f32014-06-20 12:00:00 -0700676 msg, err := c.readHandshake()
677 if err != nil {
678 return err
679 }
680 clientFinished, ok := msg.(*finishedMsg)
681 if !ok {
682 c.sendAlert(alertUnexpectedMessage)
683 return unexpectedMessageError(clientFinished, msg)
684 }
685
686 verify := hs.finishedHash.clientSum(hs.masterSecret)
687 if len(verify) != len(clientFinished.verifyData) ||
688 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
689 c.sendAlert(alertHandshakeFailure)
690 return errors.New("tls: client's Finished message is incorrect")
691 }
692
David Benjamin83c0bc92014-08-04 01:23:53 -0400693 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700694 return nil
695}
696
697func (hs *serverHandshakeState) sendSessionTicket() error {
David Benjamind23f4122014-07-23 15:09:48 -0400698 if !hs.hello.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
Adam Langley95c29f32014-06-20 12:00:00 -0700699 return nil
700 }
701
702 c := hs.c
703 m := new(newSessionTicketMsg)
704
705 var err error
706 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -0400707 vers: c.vers,
708 cipherSuite: hs.suite.id,
709 masterSecret: hs.masterSecret,
710 certificates: hs.certsFromClient,
711 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -0700712 }
713 m.ticket, err = c.encryptTicket(&state)
714 if err != nil {
715 return err
716 }
Adam Langley95c29f32014-06-20 12:00:00 -0700717
David Benjamin83c0bc92014-08-04 01:23:53 -0400718 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700719 c.writeRecord(recordTypeHandshake, m.marshal())
720
721 return nil
722}
723
724func (hs *serverHandshakeState) sendFinished() error {
725 c := hs.c
726
David Benjamin86271ee2014-07-21 16:14:03 -0400727 finished := new(finishedMsg)
728 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
729 postCCSBytes := finished.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -0400730 hs.writeServerHash(postCCSBytes)
David Benjamin86271ee2014-07-21 16:14:03 -0400731
732 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
733 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
734 postCCSBytes = postCCSBytes[5:]
735 }
736
David Benjamina0e52232014-07-19 17:39:58 -0400737 if !c.config.Bugs.SkipChangeCipherSpec {
738 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
739 }
Adam Langley95c29f32014-06-20 12:00:00 -0700740
David Benjamin86271ee2014-07-21 16:14:03 -0400741 c.writeRecord(recordTypeHandshake, postCCSBytes)
Adam Langley95c29f32014-06-20 12:00:00 -0700742
743 c.cipherSuite = hs.suite.id
744
745 return nil
746}
747
748// processCertsFromClient takes a chain of client certificates either from a
749// Certificates message or from a sessionState and verifies them. It returns
750// the public key of the leaf certificate.
751func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
752 c := hs.c
753
754 hs.certsFromClient = certificates
755 certs := make([]*x509.Certificate, len(certificates))
756 var err error
757 for i, asn1Data := range certificates {
758 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
759 c.sendAlert(alertBadCertificate)
760 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
761 }
762 }
763
764 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
765 opts := x509.VerifyOptions{
766 Roots: c.config.ClientCAs,
767 CurrentTime: c.config.time(),
768 Intermediates: x509.NewCertPool(),
769 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
770 }
771
772 for _, cert := range certs[1:] {
773 opts.Intermediates.AddCert(cert)
774 }
775
776 chains, err := certs[0].Verify(opts)
777 if err != nil {
778 c.sendAlert(alertBadCertificate)
779 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
780 }
781
782 ok := false
783 for _, ku := range certs[0].ExtKeyUsage {
784 if ku == x509.ExtKeyUsageClientAuth {
785 ok = true
786 break
787 }
788 }
789 if !ok {
790 c.sendAlert(alertHandshakeFailure)
791 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
792 }
793
794 c.verifiedChains = chains
795 }
796
797 if len(certs) > 0 {
798 var pub crypto.PublicKey
799 switch key := certs[0].PublicKey.(type) {
800 case *ecdsa.PublicKey, *rsa.PublicKey:
801 pub = key
802 default:
803 c.sendAlert(alertUnsupportedCertificate)
804 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
805 }
806 c.peerCertificates = certs
807 return pub, nil
808 }
809
810 return nil, nil
811}
812
David Benjamin83c0bc92014-08-04 01:23:53 -0400813func (hs *serverHandshakeState) writeServerHash(msg []byte) {
814 // writeServerHash is called before writeRecord.
815 hs.writeHash(msg, hs.c.sendHandshakeSeq)
816}
817
818func (hs *serverHandshakeState) writeClientHash(msg []byte) {
819 // writeClientHash is called after readHandshake.
820 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
821}
822
823func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
824 if hs.c.isDTLS {
825 // This is somewhat hacky. DTLS hashes a slightly different format.
826 // First, the TLS header.
827 hs.finishedHash.Write(msg[:4])
828 // Then the sequence number and reassembled fragment offset (always 0).
829 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
830 // Then the reassembled fragment (always equal to the message length).
831 hs.finishedHash.Write(msg[1:4])
832 // And then the message body.
833 hs.finishedHash.Write(msg[4:])
834 } else {
835 hs.finishedHash.Write(msg)
836 }
837}
838
Adam Langley95c29f32014-06-20 12:00:00 -0700839// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
840// is acceptable to use.
841func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
842 for _, supported := range supportedCipherSuites {
843 if id == supported {
844 var candidate *cipherSuite
845
846 for _, s := range cipherSuites {
847 if s.id == id {
848 candidate = s
849 break
850 }
851 }
852 if candidate == nil {
853 continue
854 }
855 // Don't select a ciphersuite which we can't
856 // support for this client.
857 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
858 continue
859 }
860 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
861 continue
862 }
David Benjamin39ebf532014-08-31 02:23:49 -0400863 if !c.config.Bugs.SkipCipherVersionCheck && version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700864 continue
865 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400866 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
867 continue
868 }
Adam Langley95c29f32014-06-20 12:00:00 -0700869 return candidate
870 }
871 }
872
873 return nil
874}