blob: 3288b0dae11413458085a46b31c2b60680a5d5fa [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 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700217
218 if len(hs.clientHello.secureRenegotiation) > 1 {
219 c.sendAlert(alertHandshakeFailure)
220 return false, errors.New("tls: client is doing a renegotiation handshake")
221 }
Adam Langley95c29f32014-06-20 12:00:00 -0700222 hs.hello.secureRenegotiation = hs.clientHello.secureRenegotiation
223 hs.hello.compressionMethod = compressionNone
David Benjamin35a7a442014-07-05 00:23:20 -0400224 hs.hello.duplicateExtension = c.config.Bugs.DuplicateExtension
Adam Langley95c29f32014-06-20 12:00:00 -0700225 if len(hs.clientHello.serverName) > 0 {
226 c.serverName = hs.clientHello.serverName
227 }
David Benjaminfa055a22014-09-15 16:51:51 -0400228
229 if len(hs.clientHello.alpnProtocols) > 0 {
230 if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
231 hs.hello.alpnProtocol = selectedProto
232 c.clientProtocol = selectedProto
David Benjaminfc7b0862014-09-06 13:21:53 -0400233 c.usedALPN = true
David Benjaminfa055a22014-09-15 16:51:51 -0400234 }
235 } else {
236 // Although sending an empty NPN extension is reasonable, Firefox has
237 // had a bug around this. Best to send nothing at all if
238 // config.NextProtos is empty. See
239 // https://code.google.com/p/go/issues/detail?id=5445.
240 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
241 hs.hello.nextProtoNeg = true
242 hs.hello.nextProtos = config.NextProtos
243 }
Adam Langley95c29f32014-06-20 12:00:00 -0700244 }
Adam Langley75712922014-10-10 16:23:43 -0700245 hs.hello.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !c.config.Bugs.NoExtendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700246
247 if len(config.Certificates) == 0 {
248 c.sendAlert(alertInternalError)
249 return false, errors.New("tls: no certificates configured")
250 }
251 hs.cert = &config.Certificates[0]
252 if len(hs.clientHello.serverName) > 0 {
253 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
254 }
David Benjamine78bfde2014-09-06 12:45:15 -0400255 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
256 return false, errors.New("tls: unexpected server name")
257 }
Adam Langley95c29f32014-06-20 12:00:00 -0700258
David Benjamind30a9902014-08-24 01:44:23 -0400259 if hs.clientHello.channelIDSupported && config.RequestChannelID {
260 hs.hello.channelIDRequested = true
261 }
262
Adam Langley95c29f32014-06-20 12:00:00 -0700263 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
264
265 if hs.checkForResumption() {
266 return true, nil
267 }
268
Adam Langleyac61fa32014-06-23 12:03:11 -0700269 var scsvFound bool
270
271 for _, cipherSuite := range hs.clientHello.cipherSuites {
272 if cipherSuite == fallbackSCSV {
273 scsvFound = true
274 break
275 }
276 }
277
278 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
279 return false, errors.New("tls: no fallback SCSV found when expected")
280 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
281 return false, errors.New("tls: fallback SCSV found when not expected")
282 }
283
Adam Langley95c29f32014-06-20 12:00:00 -0700284 var preferenceList, supportedList []uint16
285 if c.config.PreferServerCipherSuites {
286 preferenceList = c.config.cipherSuites()
287 supportedList = hs.clientHello.cipherSuites
288 } else {
289 preferenceList = hs.clientHello.cipherSuites
290 supportedList = c.config.cipherSuites()
291 }
292
293 for _, id := range preferenceList {
294 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
295 break
296 }
297 }
298
299 if hs.suite == nil {
300 c.sendAlert(alertHandshakeFailure)
301 return false, errors.New("tls: no cipher suite supported by both client and server")
302 }
303
304 return false, nil
305}
306
307// checkForResumption returns true if we should perform resumption on this connection.
308func (hs *serverHandshakeState) checkForResumption() bool {
309 c := hs.c
310
David Benjaminb0c8db72014-09-24 15:19:56 -0400311 if c.config.SessionTicketsDisabled {
312 return false
313 }
314
Adam Langley95c29f32014-06-20 12:00:00 -0700315 var ok bool
316 if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
317 return false
318 }
319
David Benjamin01fe8202014-09-24 15:21:44 -0400320 if !c.config.Bugs.AllowSessionVersionMismatch {
321 if hs.sessionState.vers > hs.clientHello.vers {
322 return false
323 }
324 if vers, ok := c.config.mutualVersion(hs.sessionState.vers); !ok || vers != hs.sessionState.vers {
325 return false
326 }
Adam Langley95c29f32014-06-20 12:00:00 -0700327 }
328
329 cipherSuiteOk := false
330 // Check that the client is still offering the ciphersuite in the session.
331 for _, id := range hs.clientHello.cipherSuites {
332 if id == hs.sessionState.cipherSuite {
333 cipherSuiteOk = true
334 break
335 }
336 }
337 if !cipherSuiteOk {
338 return false
339 }
340
341 // Check that we also support the ciphersuite from the session.
342 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk)
343 if hs.suite == nil {
344 return false
345 }
346
347 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
348 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
349 if needClientCerts && !sessionHasClientCerts {
350 return false
351 }
352 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
353 return false
354 }
355
356 return true
357}
358
359func (hs *serverHandshakeState) doResumeHandshake() error {
360 c := hs.c
361
362 hs.hello.cipherSuite = hs.suite.id
363 // We echo the client's session ID in the ServerHello to let it know
364 // that we're doing a resumption.
365 hs.hello.sessionId = hs.clientHello.sessionId
David Benjaminbed9aae2014-08-07 19:13:38 -0400366 hs.hello.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -0700367
368 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -0400369 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -0400370 hs.writeClientHash(hs.clientHello.marshal())
371 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700372
373 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
374
375 if len(hs.sessionState.certificates) > 0 {
376 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
377 return err
378 }
379 }
380
381 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -0700382 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700383
384 return nil
385}
386
387func (hs *serverHandshakeState) doFullHandshake() error {
388 config := hs.c.config
389 c := hs.c
390
David Benjamin48cae082014-10-27 01:06:24 -0400391 isPSK := hs.suite.flags&suitePSK != 0
392 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700393 hs.hello.ocspStapling = true
394 }
395
396 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled
397 hs.hello.cipherSuite = hs.suite.id
Adam Langley75712922014-10-10 16:23:43 -0700398 c.extendedMasterSecret = hs.hello.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700399
400 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400401 hs.writeClientHash(hs.clientHello.marshal())
402 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700403
404 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
405
David Benjamin48cae082014-10-27 01:06:24 -0400406 if !isPSK {
407 certMsg := new(certificateMsg)
408 certMsg.certificates = hs.cert.Certificate
409 if !config.Bugs.UnauthenticatedECDH {
410 hs.writeServerHash(certMsg.marshal())
411 c.writeRecord(recordTypeHandshake, certMsg.marshal())
412 }
David Benjamin1c375dd2014-07-12 00:48:23 -0400413 }
Adam Langley95c29f32014-06-20 12:00:00 -0700414
415 if hs.hello.ocspStapling {
416 certStatus := new(certificateStatusMsg)
417 certStatus.statusType = statusTypeOCSP
418 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -0400419 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700420 c.writeRecord(recordTypeHandshake, certStatus.marshal())
421 }
422
423 keyAgreement := hs.suite.ka(c.vers)
424 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
425 if err != nil {
426 c.sendAlert(alertHandshakeFailure)
427 return err
428 }
David Benjamin9c651c92014-07-12 13:27:45 -0400429 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -0400430 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700431 c.writeRecord(recordTypeHandshake, skx.marshal())
432 }
433
434 if config.ClientAuth >= RequestClientCert {
435 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -0400436 certReq := &certificateRequestMsg{
437 certificateTypes: config.ClientCertificateTypes,
438 }
439 if certReq.certificateTypes == nil {
440 certReq.certificateTypes = []byte{
441 byte(CertTypeRSASign),
442 byte(CertTypeECDSASign),
443 }
Adam Langley95c29f32014-06-20 12:00:00 -0700444 }
445 if c.vers >= VersionTLS12 {
446 certReq.hasSignatureAndHash = true
447 certReq.signatureAndHashes = supportedClientCertSignatureAlgorithms
448 }
449
450 // An empty list of certificateAuthorities signals to
451 // the client that it may send any certificate in response
452 // to our request. When we know the CAs we trust, then
453 // we can send them down, so that the client can choose
454 // an appropriate certificate to give to us.
455 if config.ClientCAs != nil {
456 certReq.certificateAuthorities = config.ClientCAs.Subjects()
457 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400458 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700459 c.writeRecord(recordTypeHandshake, certReq.marshal())
460 }
461
462 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400463 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700464 c.writeRecord(recordTypeHandshake, helloDone.marshal())
465
466 var pub crypto.PublicKey // public key for client auth, if any
467
468 msg, err := c.readHandshake()
469 if err != nil {
470 return err
471 }
472
473 var ok bool
474 // If we requested a client certificate, then the client must send a
475 // certificate message, even if it's empty.
476 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -0400477 var certMsg *certificateMsg
Adam Langley95c29f32014-06-20 12:00:00 -0700478 if certMsg, ok = msg.(*certificateMsg); !ok {
479 c.sendAlert(alertUnexpectedMessage)
480 return unexpectedMessageError(certMsg, msg)
481 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400482 hs.writeClientHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700483
484 if len(certMsg.certificates) == 0 {
485 // The client didn't actually send a certificate
486 switch config.ClientAuth {
487 case RequireAnyClientCert, RequireAndVerifyClientCert:
488 c.sendAlert(alertBadCertificate)
489 return errors.New("tls: client didn't provide a certificate")
490 }
491 }
492
493 pub, err = hs.processCertsFromClient(certMsg.certificates)
494 if err != nil {
495 return err
496 }
497
498 msg, err = c.readHandshake()
499 if err != nil {
500 return err
501 }
502 }
503
504 // Get client key exchange
505 ckx, ok := msg.(*clientKeyExchangeMsg)
506 if !ok {
507 c.sendAlert(alertUnexpectedMessage)
508 return unexpectedMessageError(ckx, msg)
509 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400510 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700511
David Benjamine098ec22014-08-27 23:13:20 -0400512 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
513 if err != nil {
514 c.sendAlert(alertHandshakeFailure)
515 return err
516 }
Adam Langley75712922014-10-10 16:23:43 -0700517 if c.extendedMasterSecret {
518 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
519 } else {
520 if c.config.Bugs.RequireExtendedMasterSecret {
521 return errors.New("tls: extended master secret required but not supported by peer")
522 }
523 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
524 }
David Benjamine098ec22014-08-27 23:13:20 -0400525
Adam Langley95c29f32014-06-20 12:00:00 -0700526 // If we received a client cert in response to our certificate request message,
527 // the client will send us a certificateVerifyMsg immediately after the
528 // clientKeyExchangeMsg. This message is a digest of all preceding
529 // handshake-layer messages that is signed using the private key corresponding
530 // to the client's certificate. This allows us to verify that the client is in
531 // possession of the private key of the certificate.
532 if len(c.peerCertificates) > 0 {
533 msg, err = c.readHandshake()
534 if err != nil {
535 return err
536 }
537 certVerify, ok := msg.(*certificateVerifyMsg)
538 if !ok {
539 c.sendAlert(alertUnexpectedMessage)
540 return unexpectedMessageError(certVerify, msg)
541 }
542
David Benjaminde620d92014-07-18 15:03:41 -0400543 // Determine the signature type.
544 var signatureAndHash signatureAndHash
545 if certVerify.hasSignatureAndHash {
546 signatureAndHash = certVerify.signatureAndHash
547 } else {
548 // Before TLS 1.2 the signature algorithm was implicit
549 // from the key type, and only one hash per signature
550 // algorithm was possible. Leave the hash as zero.
551 switch pub.(type) {
552 case *ecdsa.PublicKey:
553 signatureAndHash.signature = signatureECDSA
554 case *rsa.PublicKey:
555 signatureAndHash.signature = signatureRSA
556 }
557 }
558
Adam Langley95c29f32014-06-20 12:00:00 -0700559 switch key := pub.(type) {
560 case *ecdsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400561 if signatureAndHash.signature != signatureECDSA {
562 err = errors.New("tls: bad signature type for client's ECDSA certificate")
563 break
564 }
Adam Langley95c29f32014-06-20 12:00:00 -0700565 ecdsaSig := new(ecdsaSignature)
566 if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {
567 break
568 }
569 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
570 err = errors.New("ECDSA signature contained zero or negative values")
571 break
572 }
David Benjaminde620d92014-07-18 15:03:41 -0400573 var digest []byte
David Benjamine098ec22014-08-27 23:13:20 -0400574 digest, _, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400575 if err != nil {
576 break
577 }
Adam Langley95c29f32014-06-20 12:00:00 -0700578 if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {
579 err = errors.New("ECDSA verification failure")
580 break
581 }
582 case *rsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400583 if signatureAndHash.signature != signatureRSA {
584 err = errors.New("tls: bad signature type for client's RSA certificate")
585 break
586 }
587 var digest []byte
588 var hashFunc crypto.Hash
David Benjamine098ec22014-08-27 23:13:20 -0400589 digest, hashFunc, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400590 if err != nil {
591 break
592 }
Adam Langley95c29f32014-06-20 12:00:00 -0700593 err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)
594 }
595 if err != nil {
596 c.sendAlert(alertBadCertificate)
597 return errors.New("could not validate signature of connection nonces: " + err.Error())
598 }
599
David Benjamin83c0bc92014-08-04 01:23:53 -0400600 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700601 }
602
David Benjamine098ec22014-08-27 23:13:20 -0400603 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -0700604
605 return nil
606}
607
608func (hs *serverHandshakeState) establishKeys() error {
609 c := hs.c
610
611 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
612 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
613
614 var clientCipher, serverCipher interface{}
615 var clientHash, serverHash macFunction
616
617 if hs.suite.aead == nil {
618 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
619 clientHash = hs.suite.mac(c.vers, clientMAC)
620 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
621 serverHash = hs.suite.mac(c.vers, serverMAC)
622 } else {
623 clientCipher = hs.suite.aead(clientKey, clientIV)
624 serverCipher = hs.suite.aead(serverKey, serverIV)
625 }
626
627 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
628 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
629
630 return nil
631}
632
David Benjamind30a9902014-08-24 01:44:23 -0400633func (hs *serverHandshakeState) readFinished(isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700634 c := hs.c
635
636 c.readRecord(recordTypeChangeCipherSpec)
637 if err := c.in.error(); err != nil {
638 return err
639 }
640
641 if hs.hello.nextProtoNeg {
642 msg, err := c.readHandshake()
643 if err != nil {
644 return err
645 }
646 nextProto, ok := msg.(*nextProtoMsg)
647 if !ok {
648 c.sendAlert(alertUnexpectedMessage)
649 return unexpectedMessageError(nextProto, msg)
650 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400651 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700652 c.clientProtocol = nextProto.proto
653 }
654
David Benjamind30a9902014-08-24 01:44:23 -0400655 if hs.hello.channelIDRequested {
656 msg, err := c.readHandshake()
657 if err != nil {
658 return err
659 }
660 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
661 if !ok {
662 c.sendAlert(alertUnexpectedMessage)
663 return unexpectedMessageError(encryptedExtensions, msg)
664 }
665 x := new(big.Int).SetBytes(encryptedExtensions.channelID[0:32])
666 y := new(big.Int).SetBytes(encryptedExtensions.channelID[32:64])
667 r := new(big.Int).SetBytes(encryptedExtensions.channelID[64:96])
668 s := new(big.Int).SetBytes(encryptedExtensions.channelID[96:128])
669 if !elliptic.P256().IsOnCurve(x, y) {
670 return errors.New("tls: invalid channel ID public key")
671 }
672 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
673 var resumeHash []byte
674 if isResume {
675 resumeHash = hs.sessionState.handshakeHash
676 }
677 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
678 return errors.New("tls: invalid channel ID signature")
679 }
680 c.channelID = channelID
681
682 hs.writeClientHash(encryptedExtensions.marshal())
683 }
684
Adam Langley95c29f32014-06-20 12:00:00 -0700685 msg, err := c.readHandshake()
686 if err != nil {
687 return err
688 }
689 clientFinished, ok := msg.(*finishedMsg)
690 if !ok {
691 c.sendAlert(alertUnexpectedMessage)
692 return unexpectedMessageError(clientFinished, msg)
693 }
694
695 verify := hs.finishedHash.clientSum(hs.masterSecret)
696 if len(verify) != len(clientFinished.verifyData) ||
697 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
698 c.sendAlert(alertHandshakeFailure)
699 return errors.New("tls: client's Finished message is incorrect")
700 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700701 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langley95c29f32014-06-20 12:00:00 -0700702
David Benjamin83c0bc92014-08-04 01:23:53 -0400703 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700704 return nil
705}
706
707func (hs *serverHandshakeState) sendSessionTicket() error {
David Benjamind23f4122014-07-23 15:09:48 -0400708 if !hs.hello.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
Adam Langley95c29f32014-06-20 12:00:00 -0700709 return nil
710 }
711
712 c := hs.c
713 m := new(newSessionTicketMsg)
714
715 var err error
716 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -0400717 vers: c.vers,
718 cipherSuite: hs.suite.id,
719 masterSecret: hs.masterSecret,
720 certificates: hs.certsFromClient,
721 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -0700722 }
723 m.ticket, err = c.encryptTicket(&state)
724 if err != nil {
725 return err
726 }
Adam Langley95c29f32014-06-20 12:00:00 -0700727
David Benjamin83c0bc92014-08-04 01:23:53 -0400728 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700729 c.writeRecord(recordTypeHandshake, m.marshal())
730
731 return nil
732}
733
734func (hs *serverHandshakeState) sendFinished() error {
735 c := hs.c
736
David Benjamin86271ee2014-07-21 16:14:03 -0400737 finished := new(finishedMsg)
738 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
Adam Langley2ae77d22014-10-28 17:29:33 -0700739 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin86271ee2014-07-21 16:14:03 -0400740 postCCSBytes := finished.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -0400741 hs.writeServerHash(postCCSBytes)
David Benjamin86271ee2014-07-21 16:14:03 -0400742
743 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
744 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
745 postCCSBytes = postCCSBytes[5:]
746 }
747
David Benjamina0e52232014-07-19 17:39:58 -0400748 if !c.config.Bugs.SkipChangeCipherSpec {
749 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
750 }
Adam Langley95c29f32014-06-20 12:00:00 -0700751
David Benjamin86271ee2014-07-21 16:14:03 -0400752 c.writeRecord(recordTypeHandshake, postCCSBytes)
Adam Langley95c29f32014-06-20 12:00:00 -0700753
754 c.cipherSuite = hs.suite.id
755
756 return nil
757}
758
759// processCertsFromClient takes a chain of client certificates either from a
760// Certificates message or from a sessionState and verifies them. It returns
761// the public key of the leaf certificate.
762func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
763 c := hs.c
764
765 hs.certsFromClient = certificates
766 certs := make([]*x509.Certificate, len(certificates))
767 var err error
768 for i, asn1Data := range certificates {
769 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
770 c.sendAlert(alertBadCertificate)
771 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
772 }
773 }
774
775 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
776 opts := x509.VerifyOptions{
777 Roots: c.config.ClientCAs,
778 CurrentTime: c.config.time(),
779 Intermediates: x509.NewCertPool(),
780 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
781 }
782
783 for _, cert := range certs[1:] {
784 opts.Intermediates.AddCert(cert)
785 }
786
787 chains, err := certs[0].Verify(opts)
788 if err != nil {
789 c.sendAlert(alertBadCertificate)
790 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
791 }
792
793 ok := false
794 for _, ku := range certs[0].ExtKeyUsage {
795 if ku == x509.ExtKeyUsageClientAuth {
796 ok = true
797 break
798 }
799 }
800 if !ok {
801 c.sendAlert(alertHandshakeFailure)
802 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
803 }
804
805 c.verifiedChains = chains
806 }
807
808 if len(certs) > 0 {
809 var pub crypto.PublicKey
810 switch key := certs[0].PublicKey.(type) {
811 case *ecdsa.PublicKey, *rsa.PublicKey:
812 pub = key
813 default:
814 c.sendAlert(alertUnsupportedCertificate)
815 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
816 }
817 c.peerCertificates = certs
818 return pub, nil
819 }
820
821 return nil, nil
822}
823
David Benjamin83c0bc92014-08-04 01:23:53 -0400824func (hs *serverHandshakeState) writeServerHash(msg []byte) {
825 // writeServerHash is called before writeRecord.
826 hs.writeHash(msg, hs.c.sendHandshakeSeq)
827}
828
829func (hs *serverHandshakeState) writeClientHash(msg []byte) {
830 // writeClientHash is called after readHandshake.
831 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
832}
833
834func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
835 if hs.c.isDTLS {
836 // This is somewhat hacky. DTLS hashes a slightly different format.
837 // First, the TLS header.
838 hs.finishedHash.Write(msg[:4])
839 // Then the sequence number and reassembled fragment offset (always 0).
840 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
841 // Then the reassembled fragment (always equal to the message length).
842 hs.finishedHash.Write(msg[1:4])
843 // And then the message body.
844 hs.finishedHash.Write(msg[4:])
845 } else {
846 hs.finishedHash.Write(msg)
847 }
848}
849
Adam Langley95c29f32014-06-20 12:00:00 -0700850// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
851// is acceptable to use.
852func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
853 for _, supported := range supportedCipherSuites {
854 if id == supported {
855 var candidate *cipherSuite
856
857 for _, s := range cipherSuites {
858 if s.id == id {
859 candidate = s
860 break
861 }
862 }
863 if candidate == nil {
864 continue
865 }
866 // Don't select a ciphersuite which we can't
867 // support for this client.
868 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
869 continue
870 }
871 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
872 continue
873 }
David Benjamin39ebf532014-08-31 02:23:49 -0400874 if !c.config.Bugs.SkipCipherVersionCheck && version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700875 continue
876 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400877 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
878 continue
879 }
Adam Langley95c29f32014-06-20 12:00:00 -0700880 return candidate
881 }
882 }
883
884 return nil
885}