blob: 4bf8f1c1c6dc172c041747d10978c259da954b6b [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
David Benjamin48cae082014-10-27 01:06:24 -0400386 isPSK := hs.suite.flags&suitePSK != 0
387 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700388 hs.hello.ocspStapling = true
389 }
390
391 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled
392 hs.hello.cipherSuite = hs.suite.id
Adam Langley75712922014-10-10 16:23:43 -0700393 c.extendedMasterSecret = hs.hello.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700394
395 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400396 hs.writeClientHash(hs.clientHello.marshal())
397 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700398
399 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
400
David Benjamin48cae082014-10-27 01:06:24 -0400401 if !isPSK {
402 certMsg := new(certificateMsg)
403 certMsg.certificates = hs.cert.Certificate
404 if !config.Bugs.UnauthenticatedECDH {
405 hs.writeServerHash(certMsg.marshal())
406 c.writeRecord(recordTypeHandshake, certMsg.marshal())
407 }
David Benjamin1c375dd2014-07-12 00:48:23 -0400408 }
Adam Langley95c29f32014-06-20 12:00:00 -0700409
410 if hs.hello.ocspStapling {
411 certStatus := new(certificateStatusMsg)
412 certStatus.statusType = statusTypeOCSP
413 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -0400414 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700415 c.writeRecord(recordTypeHandshake, certStatus.marshal())
416 }
417
418 keyAgreement := hs.suite.ka(c.vers)
419 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
420 if err != nil {
421 c.sendAlert(alertHandshakeFailure)
422 return err
423 }
David Benjamin9c651c92014-07-12 13:27:45 -0400424 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -0400425 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700426 c.writeRecord(recordTypeHandshake, skx.marshal())
427 }
428
429 if config.ClientAuth >= RequestClientCert {
430 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -0400431 certReq := &certificateRequestMsg{
432 certificateTypes: config.ClientCertificateTypes,
433 }
434 if certReq.certificateTypes == nil {
435 certReq.certificateTypes = []byte{
436 byte(CertTypeRSASign),
437 byte(CertTypeECDSASign),
438 }
Adam Langley95c29f32014-06-20 12:00:00 -0700439 }
440 if c.vers >= VersionTLS12 {
441 certReq.hasSignatureAndHash = true
442 certReq.signatureAndHashes = supportedClientCertSignatureAlgorithms
443 }
444
445 // An empty list of certificateAuthorities signals to
446 // the client that it may send any certificate in response
447 // to our request. When we know the CAs we trust, then
448 // we can send them down, so that the client can choose
449 // an appropriate certificate to give to us.
450 if config.ClientCAs != nil {
451 certReq.certificateAuthorities = config.ClientCAs.Subjects()
452 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400453 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700454 c.writeRecord(recordTypeHandshake, certReq.marshal())
455 }
456
457 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400458 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700459 c.writeRecord(recordTypeHandshake, helloDone.marshal())
460
461 var pub crypto.PublicKey // public key for client auth, if any
462
463 msg, err := c.readHandshake()
464 if err != nil {
465 return err
466 }
467
468 var ok bool
469 // If we requested a client certificate, then the client must send a
470 // certificate message, even if it's empty.
471 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -0400472 var certMsg *certificateMsg
Adam Langley95c29f32014-06-20 12:00:00 -0700473 if certMsg, ok = msg.(*certificateMsg); !ok {
474 c.sendAlert(alertUnexpectedMessage)
475 return unexpectedMessageError(certMsg, msg)
476 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400477 hs.writeClientHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700478
479 if len(certMsg.certificates) == 0 {
480 // The client didn't actually send a certificate
481 switch config.ClientAuth {
482 case RequireAnyClientCert, RequireAndVerifyClientCert:
483 c.sendAlert(alertBadCertificate)
484 return errors.New("tls: client didn't provide a certificate")
485 }
486 }
487
488 pub, err = hs.processCertsFromClient(certMsg.certificates)
489 if err != nil {
490 return err
491 }
492
493 msg, err = c.readHandshake()
494 if err != nil {
495 return err
496 }
497 }
498
499 // Get client key exchange
500 ckx, ok := msg.(*clientKeyExchangeMsg)
501 if !ok {
502 c.sendAlert(alertUnexpectedMessage)
503 return unexpectedMessageError(ckx, msg)
504 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400505 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700506
David Benjamine098ec22014-08-27 23:13:20 -0400507 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
508 if err != nil {
509 c.sendAlert(alertHandshakeFailure)
510 return err
511 }
Adam Langley75712922014-10-10 16:23:43 -0700512 if c.extendedMasterSecret {
513 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
514 } else {
515 if c.config.Bugs.RequireExtendedMasterSecret {
516 return errors.New("tls: extended master secret required but not supported by peer")
517 }
518 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
519 }
David Benjamine098ec22014-08-27 23:13:20 -0400520
Adam Langley95c29f32014-06-20 12:00:00 -0700521 // If we received a client cert in response to our certificate request message,
522 // the client will send us a certificateVerifyMsg immediately after the
523 // clientKeyExchangeMsg. This message is a digest of all preceding
524 // handshake-layer messages that is signed using the private key corresponding
525 // to the client's certificate. This allows us to verify that the client is in
526 // possession of the private key of the certificate.
527 if len(c.peerCertificates) > 0 {
528 msg, err = c.readHandshake()
529 if err != nil {
530 return err
531 }
532 certVerify, ok := msg.(*certificateVerifyMsg)
533 if !ok {
534 c.sendAlert(alertUnexpectedMessage)
535 return unexpectedMessageError(certVerify, msg)
536 }
537
David Benjaminde620d92014-07-18 15:03:41 -0400538 // Determine the signature type.
539 var signatureAndHash signatureAndHash
540 if certVerify.hasSignatureAndHash {
541 signatureAndHash = certVerify.signatureAndHash
542 } else {
543 // Before TLS 1.2 the signature algorithm was implicit
544 // from the key type, and only one hash per signature
545 // algorithm was possible. Leave the hash as zero.
546 switch pub.(type) {
547 case *ecdsa.PublicKey:
548 signatureAndHash.signature = signatureECDSA
549 case *rsa.PublicKey:
550 signatureAndHash.signature = signatureRSA
551 }
552 }
553
Adam Langley95c29f32014-06-20 12:00:00 -0700554 switch key := pub.(type) {
555 case *ecdsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400556 if signatureAndHash.signature != signatureECDSA {
557 err = errors.New("tls: bad signature type for client's ECDSA certificate")
558 break
559 }
Adam Langley95c29f32014-06-20 12:00:00 -0700560 ecdsaSig := new(ecdsaSignature)
561 if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {
562 break
563 }
564 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
565 err = errors.New("ECDSA signature contained zero or negative values")
566 break
567 }
David Benjaminde620d92014-07-18 15:03:41 -0400568 var digest []byte
David Benjamine098ec22014-08-27 23:13:20 -0400569 digest, _, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400570 if err != nil {
571 break
572 }
Adam Langley95c29f32014-06-20 12:00:00 -0700573 if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {
574 err = errors.New("ECDSA verification failure")
575 break
576 }
577 case *rsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400578 if signatureAndHash.signature != signatureRSA {
579 err = errors.New("tls: bad signature type for client's RSA certificate")
580 break
581 }
582 var digest []byte
583 var hashFunc crypto.Hash
David Benjamine098ec22014-08-27 23:13:20 -0400584 digest, hashFunc, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400585 if err != nil {
586 break
587 }
Adam Langley95c29f32014-06-20 12:00:00 -0700588 err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)
589 }
590 if err != nil {
591 c.sendAlert(alertBadCertificate)
592 return errors.New("could not validate signature of connection nonces: " + err.Error())
593 }
594
David Benjamin83c0bc92014-08-04 01:23:53 -0400595 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700596 }
597
David Benjamine098ec22014-08-27 23:13:20 -0400598 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -0700599
600 return nil
601}
602
603func (hs *serverHandshakeState) establishKeys() error {
604 c := hs.c
605
606 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
607 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
608
609 var clientCipher, serverCipher interface{}
610 var clientHash, serverHash macFunction
611
612 if hs.suite.aead == nil {
613 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
614 clientHash = hs.suite.mac(c.vers, clientMAC)
615 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
616 serverHash = hs.suite.mac(c.vers, serverMAC)
617 } else {
618 clientCipher = hs.suite.aead(clientKey, clientIV)
619 serverCipher = hs.suite.aead(serverKey, serverIV)
620 }
621
622 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
623 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
624
625 return nil
626}
627
David Benjamind30a9902014-08-24 01:44:23 -0400628func (hs *serverHandshakeState) readFinished(isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700629 c := hs.c
630
631 c.readRecord(recordTypeChangeCipherSpec)
632 if err := c.in.error(); err != nil {
633 return err
634 }
635
636 if hs.hello.nextProtoNeg {
637 msg, err := c.readHandshake()
638 if err != nil {
639 return err
640 }
641 nextProto, ok := msg.(*nextProtoMsg)
642 if !ok {
643 c.sendAlert(alertUnexpectedMessage)
644 return unexpectedMessageError(nextProto, msg)
645 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400646 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700647 c.clientProtocol = nextProto.proto
648 }
649
David Benjamind30a9902014-08-24 01:44:23 -0400650 if hs.hello.channelIDRequested {
651 msg, err := c.readHandshake()
652 if err != nil {
653 return err
654 }
655 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
656 if !ok {
657 c.sendAlert(alertUnexpectedMessage)
658 return unexpectedMessageError(encryptedExtensions, msg)
659 }
660 x := new(big.Int).SetBytes(encryptedExtensions.channelID[0:32])
661 y := new(big.Int).SetBytes(encryptedExtensions.channelID[32:64])
662 r := new(big.Int).SetBytes(encryptedExtensions.channelID[64:96])
663 s := new(big.Int).SetBytes(encryptedExtensions.channelID[96:128])
664 if !elliptic.P256().IsOnCurve(x, y) {
665 return errors.New("tls: invalid channel ID public key")
666 }
667 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
668 var resumeHash []byte
669 if isResume {
670 resumeHash = hs.sessionState.handshakeHash
671 }
672 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
673 return errors.New("tls: invalid channel ID signature")
674 }
675 c.channelID = channelID
676
677 hs.writeClientHash(encryptedExtensions.marshal())
678 }
679
Adam Langley95c29f32014-06-20 12:00:00 -0700680 msg, err := c.readHandshake()
681 if err != nil {
682 return err
683 }
684 clientFinished, ok := msg.(*finishedMsg)
685 if !ok {
686 c.sendAlert(alertUnexpectedMessage)
687 return unexpectedMessageError(clientFinished, msg)
688 }
689
690 verify := hs.finishedHash.clientSum(hs.masterSecret)
691 if len(verify) != len(clientFinished.verifyData) ||
692 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
693 c.sendAlert(alertHandshakeFailure)
694 return errors.New("tls: client's Finished message is incorrect")
695 }
696
David Benjamin83c0bc92014-08-04 01:23:53 -0400697 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700698 return nil
699}
700
701func (hs *serverHandshakeState) sendSessionTicket() error {
David Benjamind23f4122014-07-23 15:09:48 -0400702 if !hs.hello.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
Adam Langley95c29f32014-06-20 12:00:00 -0700703 return nil
704 }
705
706 c := hs.c
707 m := new(newSessionTicketMsg)
708
709 var err error
710 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -0400711 vers: c.vers,
712 cipherSuite: hs.suite.id,
713 masterSecret: hs.masterSecret,
714 certificates: hs.certsFromClient,
715 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -0700716 }
717 m.ticket, err = c.encryptTicket(&state)
718 if err != nil {
719 return err
720 }
Adam Langley95c29f32014-06-20 12:00:00 -0700721
David Benjamin83c0bc92014-08-04 01:23:53 -0400722 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700723 c.writeRecord(recordTypeHandshake, m.marshal())
724
725 return nil
726}
727
728func (hs *serverHandshakeState) sendFinished() error {
729 c := hs.c
730
David Benjamin86271ee2014-07-21 16:14:03 -0400731 finished := new(finishedMsg)
732 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
733 postCCSBytes := finished.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -0400734 hs.writeServerHash(postCCSBytes)
David Benjamin86271ee2014-07-21 16:14:03 -0400735
736 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
737 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
738 postCCSBytes = postCCSBytes[5:]
739 }
740
David Benjamina0e52232014-07-19 17:39:58 -0400741 if !c.config.Bugs.SkipChangeCipherSpec {
742 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
743 }
Adam Langley95c29f32014-06-20 12:00:00 -0700744
David Benjamin86271ee2014-07-21 16:14:03 -0400745 c.writeRecord(recordTypeHandshake, postCCSBytes)
Adam Langley95c29f32014-06-20 12:00:00 -0700746
747 c.cipherSuite = hs.suite.id
748
749 return nil
750}
751
752// processCertsFromClient takes a chain of client certificates either from a
753// Certificates message or from a sessionState and verifies them. It returns
754// the public key of the leaf certificate.
755func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
756 c := hs.c
757
758 hs.certsFromClient = certificates
759 certs := make([]*x509.Certificate, len(certificates))
760 var err error
761 for i, asn1Data := range certificates {
762 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
763 c.sendAlert(alertBadCertificate)
764 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
765 }
766 }
767
768 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
769 opts := x509.VerifyOptions{
770 Roots: c.config.ClientCAs,
771 CurrentTime: c.config.time(),
772 Intermediates: x509.NewCertPool(),
773 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
774 }
775
776 for _, cert := range certs[1:] {
777 opts.Intermediates.AddCert(cert)
778 }
779
780 chains, err := certs[0].Verify(opts)
781 if err != nil {
782 c.sendAlert(alertBadCertificate)
783 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
784 }
785
786 ok := false
787 for _, ku := range certs[0].ExtKeyUsage {
788 if ku == x509.ExtKeyUsageClientAuth {
789 ok = true
790 break
791 }
792 }
793 if !ok {
794 c.sendAlert(alertHandshakeFailure)
795 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
796 }
797
798 c.verifiedChains = chains
799 }
800
801 if len(certs) > 0 {
802 var pub crypto.PublicKey
803 switch key := certs[0].PublicKey.(type) {
804 case *ecdsa.PublicKey, *rsa.PublicKey:
805 pub = key
806 default:
807 c.sendAlert(alertUnsupportedCertificate)
808 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
809 }
810 c.peerCertificates = certs
811 return pub, nil
812 }
813
814 return nil, nil
815}
816
David Benjamin83c0bc92014-08-04 01:23:53 -0400817func (hs *serverHandshakeState) writeServerHash(msg []byte) {
818 // writeServerHash is called before writeRecord.
819 hs.writeHash(msg, hs.c.sendHandshakeSeq)
820}
821
822func (hs *serverHandshakeState) writeClientHash(msg []byte) {
823 // writeClientHash is called after readHandshake.
824 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
825}
826
827func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
828 if hs.c.isDTLS {
829 // This is somewhat hacky. DTLS hashes a slightly different format.
830 // First, the TLS header.
831 hs.finishedHash.Write(msg[:4])
832 // Then the sequence number and reassembled fragment offset (always 0).
833 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
834 // Then the reassembled fragment (always equal to the message length).
835 hs.finishedHash.Write(msg[1:4])
836 // And then the message body.
837 hs.finishedHash.Write(msg[4:])
838 } else {
839 hs.finishedHash.Write(msg)
840 }
841}
842
Adam Langley95c29f32014-06-20 12:00:00 -0700843// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
844// is acceptable to use.
845func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
846 for _, supported := range supportedCipherSuites {
847 if id == supported {
848 var candidate *cipherSuite
849
850 for _, s := range cipherSuites {
851 if s.id == id {
852 candidate = s
853 break
854 }
855 }
856 if candidate == nil {
857 continue
858 }
859 // Don't select a ciphersuite which we can't
860 // support for this client.
861 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
862 continue
863 }
864 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
865 continue
866 }
David Benjamin39ebf532014-08-31 02:23:49 -0400867 if !c.config.Bugs.SkipCipherVersionCheck && version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700868 continue
869 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400870 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
871 continue
872 }
Adam Langley95c29f32014-06-20 12:00:00 -0700873 return candidate
874 }
875 }
876
877 return nil
878}