blob: 32814d3b59993638498a8aa98b31efa6e010097c [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
Adam Langleycf2d4f42014-10-28 19:06:14 -0700218 if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) {
Adam Langley2ae77d22014-10-28 17:29:33 -0700219 c.sendAlert(alertHandshakeFailure)
Adam Langleycf2d4f42014-10-28 19:06:14 -0700220 return false, errors.New("tls: renegotiation mismatch")
Adam Langley2ae77d22014-10-28 17:29:33 -0700221 }
Adam Langleycf2d4f42014-10-28 19:06:14 -0700222
223 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
224 hs.hello.secureRenegotiation = append(hs.hello.secureRenegotiation, c.clientVerify...)
225 hs.hello.secureRenegotiation = append(hs.hello.secureRenegotiation, c.serverVerify...)
226 if c.config.Bugs.BadRenegotiationInfo {
227 hs.hello.secureRenegotiation[0] ^= 0x80
228 }
229 } else {
230 hs.hello.secureRenegotiation = hs.clientHello.secureRenegotiation
231 }
232
Adam Langley95c29f32014-06-20 12:00:00 -0700233 hs.hello.compressionMethod = compressionNone
David Benjamin35a7a442014-07-05 00:23:20 -0400234 hs.hello.duplicateExtension = c.config.Bugs.DuplicateExtension
Adam Langley95c29f32014-06-20 12:00:00 -0700235 if len(hs.clientHello.serverName) > 0 {
236 c.serverName = hs.clientHello.serverName
237 }
David Benjaminfa055a22014-09-15 16:51:51 -0400238
239 if len(hs.clientHello.alpnProtocols) > 0 {
240 if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
241 hs.hello.alpnProtocol = selectedProto
242 c.clientProtocol = selectedProto
David Benjaminfc7b0862014-09-06 13:21:53 -0400243 c.usedALPN = true
David Benjaminfa055a22014-09-15 16:51:51 -0400244 }
245 } else {
246 // Although sending an empty NPN extension is reasonable, Firefox has
247 // had a bug around this. Best to send nothing at all if
248 // config.NextProtos is empty. See
249 // https://code.google.com/p/go/issues/detail?id=5445.
250 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
251 hs.hello.nextProtoNeg = true
252 hs.hello.nextProtos = config.NextProtos
253 }
Adam Langley95c29f32014-06-20 12:00:00 -0700254 }
Adam Langley75712922014-10-10 16:23:43 -0700255 hs.hello.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !c.config.Bugs.NoExtendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700256
257 if len(config.Certificates) == 0 {
258 c.sendAlert(alertInternalError)
259 return false, errors.New("tls: no certificates configured")
260 }
261 hs.cert = &config.Certificates[0]
262 if len(hs.clientHello.serverName) > 0 {
263 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
264 }
David Benjamine78bfde2014-09-06 12:45:15 -0400265 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
266 return false, errors.New("tls: unexpected server name")
267 }
Adam Langley95c29f32014-06-20 12:00:00 -0700268
David Benjamind30a9902014-08-24 01:44:23 -0400269 if hs.clientHello.channelIDSupported && config.RequestChannelID {
270 hs.hello.channelIDRequested = true
271 }
272
David Benjaminca6c8262014-11-15 19:06:08 -0500273 if hs.clientHello.srtpProtectionProfiles != nil {
274 SRTPLoop:
275 for _, p1 := range c.config.SRTPProtectionProfiles {
276 for _, p2 := range hs.clientHello.srtpProtectionProfiles {
277 if p1 == p2 {
278 hs.hello.srtpProtectionProfile = p1
279 c.srtpProtectionProfile = p1
280 break SRTPLoop
281 }
282 }
283 }
284 }
285
286 if c.config.Bugs.SendSRTPProtectionProfile != 0 {
287 hs.hello.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
288 }
289
Adam Langley95c29f32014-06-20 12:00:00 -0700290 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
291
292 if hs.checkForResumption() {
293 return true, nil
294 }
295
Adam Langleyac61fa32014-06-23 12:03:11 -0700296 var scsvFound bool
297
298 for _, cipherSuite := range hs.clientHello.cipherSuites {
299 if cipherSuite == fallbackSCSV {
300 scsvFound = true
301 break
302 }
303 }
304
305 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
306 return false, errors.New("tls: no fallback SCSV found when expected")
307 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
308 return false, errors.New("tls: fallback SCSV found when not expected")
309 }
310
Adam Langley95c29f32014-06-20 12:00:00 -0700311 var preferenceList, supportedList []uint16
312 if c.config.PreferServerCipherSuites {
313 preferenceList = c.config.cipherSuites()
314 supportedList = hs.clientHello.cipherSuites
315 } else {
316 preferenceList = hs.clientHello.cipherSuites
317 supportedList = c.config.cipherSuites()
318 }
319
320 for _, id := range preferenceList {
321 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
322 break
323 }
324 }
325
326 if hs.suite == nil {
327 c.sendAlert(alertHandshakeFailure)
328 return false, errors.New("tls: no cipher suite supported by both client and server")
329 }
330
331 return false, nil
332}
333
334// checkForResumption returns true if we should perform resumption on this connection.
335func (hs *serverHandshakeState) checkForResumption() bool {
336 c := hs.c
337
David Benjaminb0c8db72014-09-24 15:19:56 -0400338 if c.config.SessionTicketsDisabled {
339 return false
340 }
341
Adam Langley95c29f32014-06-20 12:00:00 -0700342 var ok bool
343 if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
344 return false
345 }
346
David Benjamine18d8212014-11-10 02:37:15 -0500347 // Never resume a session for a different SSL version.
348 if !c.config.Bugs.AllowSessionVersionMismatch && c.vers != hs.sessionState.vers {
349 return false
Adam Langley95c29f32014-06-20 12:00:00 -0700350 }
351
352 cipherSuiteOk := false
353 // Check that the client is still offering the ciphersuite in the session.
354 for _, id := range hs.clientHello.cipherSuites {
355 if id == hs.sessionState.cipherSuite {
356 cipherSuiteOk = true
357 break
358 }
359 }
360 if !cipherSuiteOk {
361 return false
362 }
363
364 // Check that we also support the ciphersuite from the session.
365 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk)
366 if hs.suite == nil {
367 return false
368 }
369
370 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
371 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
372 if needClientCerts && !sessionHasClientCerts {
373 return false
374 }
375 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
376 return false
377 }
378
379 return true
380}
381
382func (hs *serverHandshakeState) doResumeHandshake() error {
383 c := hs.c
384
385 hs.hello.cipherSuite = hs.suite.id
386 // We echo the client's session ID in the ServerHello to let it know
387 // that we're doing a resumption.
388 hs.hello.sessionId = hs.clientHello.sessionId
David Benjaminbed9aae2014-08-07 19:13:38 -0400389 hs.hello.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -0700390
391 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -0400392 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -0400393 hs.writeClientHash(hs.clientHello.marshal())
394 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700395
396 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
397
398 if len(hs.sessionState.certificates) > 0 {
399 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
400 return err
401 }
402 }
403
404 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -0700405 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700406
407 return nil
408}
409
410func (hs *serverHandshakeState) doFullHandshake() error {
411 config := hs.c.config
412 c := hs.c
413
David Benjamin48cae082014-10-27 01:06:24 -0400414 isPSK := hs.suite.flags&suitePSK != 0
415 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700416 hs.hello.ocspStapling = true
417 }
418
419 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled
420 hs.hello.cipherSuite = hs.suite.id
Adam Langley75712922014-10-10 16:23:43 -0700421 c.extendedMasterSecret = hs.hello.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700422
423 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400424 hs.writeClientHash(hs.clientHello.marshal())
425 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700426
427 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
428
David Benjamin48cae082014-10-27 01:06:24 -0400429 if !isPSK {
430 certMsg := new(certificateMsg)
431 certMsg.certificates = hs.cert.Certificate
432 if !config.Bugs.UnauthenticatedECDH {
433 hs.writeServerHash(certMsg.marshal())
434 c.writeRecord(recordTypeHandshake, certMsg.marshal())
435 }
David Benjamin1c375dd2014-07-12 00:48:23 -0400436 }
Adam Langley95c29f32014-06-20 12:00:00 -0700437
438 if hs.hello.ocspStapling {
439 certStatus := new(certificateStatusMsg)
440 certStatus.statusType = statusTypeOCSP
441 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -0400442 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700443 c.writeRecord(recordTypeHandshake, certStatus.marshal())
444 }
445
446 keyAgreement := hs.suite.ka(c.vers)
447 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
448 if err != nil {
449 c.sendAlert(alertHandshakeFailure)
450 return err
451 }
David Benjamin9c651c92014-07-12 13:27:45 -0400452 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -0400453 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700454 c.writeRecord(recordTypeHandshake, skx.marshal())
455 }
456
457 if config.ClientAuth >= RequestClientCert {
458 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -0400459 certReq := &certificateRequestMsg{
460 certificateTypes: config.ClientCertificateTypes,
461 }
462 if certReq.certificateTypes == nil {
463 certReq.certificateTypes = []byte{
464 byte(CertTypeRSASign),
465 byte(CertTypeECDSASign),
466 }
Adam Langley95c29f32014-06-20 12:00:00 -0700467 }
468 if c.vers >= VersionTLS12 {
469 certReq.hasSignatureAndHash = true
David Benjamin000800a2014-11-14 01:43:59 -0500470 if !config.Bugs.NoSignatureAndHashes {
471 certReq.signatureAndHashes = config.signatureAndHashesForServer()
472 }
Adam Langley95c29f32014-06-20 12:00:00 -0700473 }
474
475 // An empty list of certificateAuthorities signals to
476 // the client that it may send any certificate in response
477 // to our request. When we know the CAs we trust, then
478 // we can send them down, so that the client can choose
479 // an appropriate certificate to give to us.
480 if config.ClientCAs != nil {
481 certReq.certificateAuthorities = config.ClientCAs.Subjects()
482 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400483 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700484 c.writeRecord(recordTypeHandshake, certReq.marshal())
485 }
486
487 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400488 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700489 c.writeRecord(recordTypeHandshake, helloDone.marshal())
490
491 var pub crypto.PublicKey // public key for client auth, if any
492
493 msg, err := c.readHandshake()
494 if err != nil {
495 return err
496 }
497
498 var ok bool
499 // If we requested a client certificate, then the client must send a
500 // certificate message, even if it's empty.
501 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -0400502 var certMsg *certificateMsg
Adam Langley95c29f32014-06-20 12:00:00 -0700503 if certMsg, ok = msg.(*certificateMsg); !ok {
504 c.sendAlert(alertUnexpectedMessage)
505 return unexpectedMessageError(certMsg, msg)
506 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400507 hs.writeClientHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700508
509 if len(certMsg.certificates) == 0 {
510 // The client didn't actually send a certificate
511 switch config.ClientAuth {
512 case RequireAnyClientCert, RequireAndVerifyClientCert:
513 c.sendAlert(alertBadCertificate)
514 return errors.New("tls: client didn't provide a certificate")
515 }
516 }
517
518 pub, err = hs.processCertsFromClient(certMsg.certificates)
519 if err != nil {
520 return err
521 }
522
523 msg, err = c.readHandshake()
524 if err != nil {
525 return err
526 }
527 }
528
529 // Get client key exchange
530 ckx, ok := msg.(*clientKeyExchangeMsg)
531 if !ok {
532 c.sendAlert(alertUnexpectedMessage)
533 return unexpectedMessageError(ckx, msg)
534 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400535 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700536
David Benjamine098ec22014-08-27 23:13:20 -0400537 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
538 if err != nil {
539 c.sendAlert(alertHandshakeFailure)
540 return err
541 }
Adam Langley75712922014-10-10 16:23:43 -0700542 if c.extendedMasterSecret {
543 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
544 } else {
545 if c.config.Bugs.RequireExtendedMasterSecret {
546 return errors.New("tls: extended master secret required but not supported by peer")
547 }
548 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
549 }
David Benjamine098ec22014-08-27 23:13:20 -0400550
Adam Langley95c29f32014-06-20 12:00:00 -0700551 // If we received a client cert in response to our certificate request message,
552 // the client will send us a certificateVerifyMsg immediately after the
553 // clientKeyExchangeMsg. This message is a digest of all preceding
554 // handshake-layer messages that is signed using the private key corresponding
555 // to the client's certificate. This allows us to verify that the client is in
556 // possession of the private key of the certificate.
557 if len(c.peerCertificates) > 0 {
558 msg, err = c.readHandshake()
559 if err != nil {
560 return err
561 }
562 certVerify, ok := msg.(*certificateVerifyMsg)
563 if !ok {
564 c.sendAlert(alertUnexpectedMessage)
565 return unexpectedMessageError(certVerify, msg)
566 }
567
David Benjaminde620d92014-07-18 15:03:41 -0400568 // Determine the signature type.
569 var signatureAndHash signatureAndHash
570 if certVerify.hasSignatureAndHash {
571 signatureAndHash = certVerify.signatureAndHash
David Benjamin000800a2014-11-14 01:43:59 -0500572 if !isSupportedSignatureAndHash(signatureAndHash, config.signatureAndHashesForServer()) {
573 return errors.New("tls: unsupported hash function for client certificate")
574 }
David Benjaminde620d92014-07-18 15:03:41 -0400575 } else {
576 // Before TLS 1.2 the signature algorithm was implicit
577 // from the key type, and only one hash per signature
578 // algorithm was possible. Leave the hash as zero.
579 switch pub.(type) {
580 case *ecdsa.PublicKey:
581 signatureAndHash.signature = signatureECDSA
582 case *rsa.PublicKey:
583 signatureAndHash.signature = signatureRSA
584 }
585 }
586
Adam Langley95c29f32014-06-20 12:00:00 -0700587 switch key := pub.(type) {
588 case *ecdsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400589 if signatureAndHash.signature != signatureECDSA {
590 err = errors.New("tls: bad signature type for client's ECDSA certificate")
591 break
592 }
Adam Langley95c29f32014-06-20 12:00:00 -0700593 ecdsaSig := new(ecdsaSignature)
594 if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {
595 break
596 }
597 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
598 err = errors.New("ECDSA signature contained zero or negative values")
599 break
600 }
David Benjaminde620d92014-07-18 15:03:41 -0400601 var digest []byte
David Benjamine098ec22014-08-27 23:13:20 -0400602 digest, _, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400603 if err != nil {
604 break
605 }
Adam Langley95c29f32014-06-20 12:00:00 -0700606 if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {
607 err = errors.New("ECDSA verification failure")
608 break
609 }
610 case *rsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400611 if signatureAndHash.signature != signatureRSA {
612 err = errors.New("tls: bad signature type for client's RSA certificate")
613 break
614 }
615 var digest []byte
616 var hashFunc crypto.Hash
David Benjamine098ec22014-08-27 23:13:20 -0400617 digest, hashFunc, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400618 if err != nil {
619 break
620 }
Adam Langley95c29f32014-06-20 12:00:00 -0700621 err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)
622 }
623 if err != nil {
624 c.sendAlert(alertBadCertificate)
625 return errors.New("could not validate signature of connection nonces: " + err.Error())
626 }
627
David Benjamin83c0bc92014-08-04 01:23:53 -0400628 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700629 }
630
David Benjamine098ec22014-08-27 23:13:20 -0400631 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -0700632
633 return nil
634}
635
636func (hs *serverHandshakeState) establishKeys() error {
637 c := hs.c
638
639 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
640 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
641
642 var clientCipher, serverCipher interface{}
643 var clientHash, serverHash macFunction
644
645 if hs.suite.aead == nil {
646 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
647 clientHash = hs.suite.mac(c.vers, clientMAC)
648 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
649 serverHash = hs.suite.mac(c.vers, serverMAC)
650 } else {
651 clientCipher = hs.suite.aead(clientKey, clientIV)
652 serverCipher = hs.suite.aead(serverKey, serverIV)
653 }
654
655 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
656 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
657
658 return nil
659}
660
David Benjamind30a9902014-08-24 01:44:23 -0400661func (hs *serverHandshakeState) readFinished(isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700662 c := hs.c
663
664 c.readRecord(recordTypeChangeCipherSpec)
665 if err := c.in.error(); err != nil {
666 return err
667 }
668
669 if hs.hello.nextProtoNeg {
670 msg, err := c.readHandshake()
671 if err != nil {
672 return err
673 }
674 nextProto, ok := msg.(*nextProtoMsg)
675 if !ok {
676 c.sendAlert(alertUnexpectedMessage)
677 return unexpectedMessageError(nextProto, msg)
678 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400679 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700680 c.clientProtocol = nextProto.proto
681 }
682
David Benjamind30a9902014-08-24 01:44:23 -0400683 if hs.hello.channelIDRequested {
684 msg, err := c.readHandshake()
685 if err != nil {
686 return err
687 }
688 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
689 if !ok {
690 c.sendAlert(alertUnexpectedMessage)
691 return unexpectedMessageError(encryptedExtensions, msg)
692 }
693 x := new(big.Int).SetBytes(encryptedExtensions.channelID[0:32])
694 y := new(big.Int).SetBytes(encryptedExtensions.channelID[32:64])
695 r := new(big.Int).SetBytes(encryptedExtensions.channelID[64:96])
696 s := new(big.Int).SetBytes(encryptedExtensions.channelID[96:128])
697 if !elliptic.P256().IsOnCurve(x, y) {
698 return errors.New("tls: invalid channel ID public key")
699 }
700 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
701 var resumeHash []byte
702 if isResume {
703 resumeHash = hs.sessionState.handshakeHash
704 }
705 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
706 return errors.New("tls: invalid channel ID signature")
707 }
708 c.channelID = channelID
709
710 hs.writeClientHash(encryptedExtensions.marshal())
711 }
712
Adam Langley95c29f32014-06-20 12:00:00 -0700713 msg, err := c.readHandshake()
714 if err != nil {
715 return err
716 }
717 clientFinished, ok := msg.(*finishedMsg)
718 if !ok {
719 c.sendAlert(alertUnexpectedMessage)
720 return unexpectedMessageError(clientFinished, msg)
721 }
722
723 verify := hs.finishedHash.clientSum(hs.masterSecret)
724 if len(verify) != len(clientFinished.verifyData) ||
725 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
726 c.sendAlert(alertHandshakeFailure)
727 return errors.New("tls: client's Finished message is incorrect")
728 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700729 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langley95c29f32014-06-20 12:00:00 -0700730
David Benjamin83c0bc92014-08-04 01:23:53 -0400731 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700732 return nil
733}
734
735func (hs *serverHandshakeState) sendSessionTicket() error {
David Benjamind23f4122014-07-23 15:09:48 -0400736 if !hs.hello.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
Adam Langley95c29f32014-06-20 12:00:00 -0700737 return nil
738 }
739
740 c := hs.c
741 m := new(newSessionTicketMsg)
742
743 var err error
744 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -0400745 vers: c.vers,
746 cipherSuite: hs.suite.id,
747 masterSecret: hs.masterSecret,
748 certificates: hs.certsFromClient,
749 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -0700750 }
751 m.ticket, err = c.encryptTicket(&state)
752 if err != nil {
753 return err
754 }
Adam Langley95c29f32014-06-20 12:00:00 -0700755
David Benjamin83c0bc92014-08-04 01:23:53 -0400756 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700757 c.writeRecord(recordTypeHandshake, m.marshal())
758
759 return nil
760}
761
762func (hs *serverHandshakeState) sendFinished() error {
763 c := hs.c
764
David Benjamin86271ee2014-07-21 16:14:03 -0400765 finished := new(finishedMsg)
766 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
Adam Langley2ae77d22014-10-28 17:29:33 -0700767 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin86271ee2014-07-21 16:14:03 -0400768 postCCSBytes := finished.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -0400769 hs.writeServerHash(postCCSBytes)
David Benjamin86271ee2014-07-21 16:14:03 -0400770
771 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
772 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
773 postCCSBytes = postCCSBytes[5:]
774 }
775
David Benjamina0e52232014-07-19 17:39:58 -0400776 if !c.config.Bugs.SkipChangeCipherSpec {
777 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
778 }
Adam Langley95c29f32014-06-20 12:00:00 -0700779
David Benjamin86271ee2014-07-21 16:14:03 -0400780 c.writeRecord(recordTypeHandshake, postCCSBytes)
Adam Langley95c29f32014-06-20 12:00:00 -0700781
782 c.cipherSuite = hs.suite.id
783
784 return nil
785}
786
787// processCertsFromClient takes a chain of client certificates either from a
788// Certificates message or from a sessionState and verifies them. It returns
789// the public key of the leaf certificate.
790func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
791 c := hs.c
792
793 hs.certsFromClient = certificates
794 certs := make([]*x509.Certificate, len(certificates))
795 var err error
796 for i, asn1Data := range certificates {
797 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
798 c.sendAlert(alertBadCertificate)
799 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
800 }
801 }
802
803 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
804 opts := x509.VerifyOptions{
805 Roots: c.config.ClientCAs,
806 CurrentTime: c.config.time(),
807 Intermediates: x509.NewCertPool(),
808 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
809 }
810
811 for _, cert := range certs[1:] {
812 opts.Intermediates.AddCert(cert)
813 }
814
815 chains, err := certs[0].Verify(opts)
816 if err != nil {
817 c.sendAlert(alertBadCertificate)
818 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
819 }
820
821 ok := false
822 for _, ku := range certs[0].ExtKeyUsage {
823 if ku == x509.ExtKeyUsageClientAuth {
824 ok = true
825 break
826 }
827 }
828 if !ok {
829 c.sendAlert(alertHandshakeFailure)
830 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
831 }
832
833 c.verifiedChains = chains
834 }
835
836 if len(certs) > 0 {
837 var pub crypto.PublicKey
838 switch key := certs[0].PublicKey.(type) {
839 case *ecdsa.PublicKey, *rsa.PublicKey:
840 pub = key
841 default:
842 c.sendAlert(alertUnsupportedCertificate)
843 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
844 }
845 c.peerCertificates = certs
846 return pub, nil
847 }
848
849 return nil, nil
850}
851
David Benjamin83c0bc92014-08-04 01:23:53 -0400852func (hs *serverHandshakeState) writeServerHash(msg []byte) {
853 // writeServerHash is called before writeRecord.
854 hs.writeHash(msg, hs.c.sendHandshakeSeq)
855}
856
857func (hs *serverHandshakeState) writeClientHash(msg []byte) {
858 // writeClientHash is called after readHandshake.
859 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
860}
861
862func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
863 if hs.c.isDTLS {
864 // This is somewhat hacky. DTLS hashes a slightly different format.
865 // First, the TLS header.
866 hs.finishedHash.Write(msg[:4])
867 // Then the sequence number and reassembled fragment offset (always 0).
868 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
869 // Then the reassembled fragment (always equal to the message length).
870 hs.finishedHash.Write(msg[1:4])
871 // And then the message body.
872 hs.finishedHash.Write(msg[4:])
873 } else {
874 hs.finishedHash.Write(msg)
875 }
876}
877
Adam Langley95c29f32014-06-20 12:00:00 -0700878// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
879// is acceptable to use.
880func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
881 for _, supported := range supportedCipherSuites {
882 if id == supported {
883 var candidate *cipherSuite
884
885 for _, s := range cipherSuites {
886 if s.id == id {
887 candidate = s
888 break
889 }
890 }
891 if candidate == nil {
892 continue
893 }
894 // Don't select a ciphersuite which we can't
895 // support for this client.
896 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
897 continue
898 }
899 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
900 continue
901 }
David Benjamin39ebf532014-08-31 02:23:49 -0400902 if !c.config.Bugs.SkipCipherVersionCheck && version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700903 continue
904 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400905 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
906 continue
907 }
Adam Langley95c29f32014-06-20 12:00:00 -0700908 return candidate
909 }
910 }
911
912 return nil
913}