blob: 41d588aad33c424c81f85e0be625866d4efa72d4 [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
Adam Langley95c29f32014-06-20 12:00:00 -0700273 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
274
275 if hs.checkForResumption() {
276 return true, nil
277 }
278
Adam Langleyac61fa32014-06-23 12:03:11 -0700279 var scsvFound bool
280
281 for _, cipherSuite := range hs.clientHello.cipherSuites {
282 if cipherSuite == fallbackSCSV {
283 scsvFound = true
284 break
285 }
286 }
287
288 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
289 return false, errors.New("tls: no fallback SCSV found when expected")
290 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
291 return false, errors.New("tls: fallback SCSV found when not expected")
292 }
293
Adam Langley95c29f32014-06-20 12:00:00 -0700294 var preferenceList, supportedList []uint16
295 if c.config.PreferServerCipherSuites {
296 preferenceList = c.config.cipherSuites()
297 supportedList = hs.clientHello.cipherSuites
298 } else {
299 preferenceList = hs.clientHello.cipherSuites
300 supportedList = c.config.cipherSuites()
301 }
302
303 for _, id := range preferenceList {
304 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
305 break
306 }
307 }
308
309 if hs.suite == nil {
310 c.sendAlert(alertHandshakeFailure)
311 return false, errors.New("tls: no cipher suite supported by both client and server")
312 }
313
314 return false, nil
315}
316
317// checkForResumption returns true if we should perform resumption on this connection.
318func (hs *serverHandshakeState) checkForResumption() bool {
319 c := hs.c
320
David Benjaminb0c8db72014-09-24 15:19:56 -0400321 if c.config.SessionTicketsDisabled {
322 return false
323 }
324
Adam Langley95c29f32014-06-20 12:00:00 -0700325 var ok bool
326 if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
327 return false
328 }
329
David Benjamin01fe8202014-09-24 15:21:44 -0400330 if !c.config.Bugs.AllowSessionVersionMismatch {
331 if hs.sessionState.vers > hs.clientHello.vers {
332 return false
333 }
334 if vers, ok := c.config.mutualVersion(hs.sessionState.vers); !ok || vers != hs.sessionState.vers {
335 return false
336 }
Adam Langley95c29f32014-06-20 12:00:00 -0700337 }
338
339 cipherSuiteOk := false
340 // Check that the client is still offering the ciphersuite in the session.
341 for _, id := range hs.clientHello.cipherSuites {
342 if id == hs.sessionState.cipherSuite {
343 cipherSuiteOk = true
344 break
345 }
346 }
347 if !cipherSuiteOk {
348 return false
349 }
350
351 // Check that we also support the ciphersuite from the session.
352 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk)
353 if hs.suite == nil {
354 return false
355 }
356
357 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
358 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
359 if needClientCerts && !sessionHasClientCerts {
360 return false
361 }
362 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
363 return false
364 }
365
366 return true
367}
368
369func (hs *serverHandshakeState) doResumeHandshake() error {
370 c := hs.c
371
372 hs.hello.cipherSuite = hs.suite.id
373 // We echo the client's session ID in the ServerHello to let it know
374 // that we're doing a resumption.
375 hs.hello.sessionId = hs.clientHello.sessionId
David Benjaminbed9aae2014-08-07 19:13:38 -0400376 hs.hello.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -0700377
378 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -0400379 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -0400380 hs.writeClientHash(hs.clientHello.marshal())
381 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700382
383 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
384
385 if len(hs.sessionState.certificates) > 0 {
386 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
387 return err
388 }
389 }
390
391 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -0700392 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700393
394 return nil
395}
396
397func (hs *serverHandshakeState) doFullHandshake() error {
398 config := hs.c.config
399 c := hs.c
400
David Benjamin48cae082014-10-27 01:06:24 -0400401 isPSK := hs.suite.flags&suitePSK != 0
402 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700403 hs.hello.ocspStapling = true
404 }
405
406 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled
407 hs.hello.cipherSuite = hs.suite.id
Adam Langley75712922014-10-10 16:23:43 -0700408 c.extendedMasterSecret = hs.hello.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700409
410 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400411 hs.writeClientHash(hs.clientHello.marshal())
412 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700413
414 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
415
David Benjamin48cae082014-10-27 01:06:24 -0400416 if !isPSK {
417 certMsg := new(certificateMsg)
418 certMsg.certificates = hs.cert.Certificate
419 if !config.Bugs.UnauthenticatedECDH {
420 hs.writeServerHash(certMsg.marshal())
421 c.writeRecord(recordTypeHandshake, certMsg.marshal())
422 }
David Benjamin1c375dd2014-07-12 00:48:23 -0400423 }
Adam Langley95c29f32014-06-20 12:00:00 -0700424
425 if hs.hello.ocspStapling {
426 certStatus := new(certificateStatusMsg)
427 certStatus.statusType = statusTypeOCSP
428 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -0400429 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700430 c.writeRecord(recordTypeHandshake, certStatus.marshal())
431 }
432
433 keyAgreement := hs.suite.ka(c.vers)
434 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
435 if err != nil {
436 c.sendAlert(alertHandshakeFailure)
437 return err
438 }
David Benjamin9c651c92014-07-12 13:27:45 -0400439 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -0400440 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700441 c.writeRecord(recordTypeHandshake, skx.marshal())
442 }
443
444 if config.ClientAuth >= RequestClientCert {
445 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -0400446 certReq := &certificateRequestMsg{
447 certificateTypes: config.ClientCertificateTypes,
448 }
449 if certReq.certificateTypes == nil {
450 certReq.certificateTypes = []byte{
451 byte(CertTypeRSASign),
452 byte(CertTypeECDSASign),
453 }
Adam Langley95c29f32014-06-20 12:00:00 -0700454 }
455 if c.vers >= VersionTLS12 {
456 certReq.hasSignatureAndHash = true
457 certReq.signatureAndHashes = supportedClientCertSignatureAlgorithms
458 }
459
460 // An empty list of certificateAuthorities signals to
461 // the client that it may send any certificate in response
462 // to our request. When we know the CAs we trust, then
463 // we can send them down, so that the client can choose
464 // an appropriate certificate to give to us.
465 if config.ClientCAs != nil {
466 certReq.certificateAuthorities = config.ClientCAs.Subjects()
467 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400468 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700469 c.writeRecord(recordTypeHandshake, certReq.marshal())
470 }
471
472 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400473 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700474 c.writeRecord(recordTypeHandshake, helloDone.marshal())
475
476 var pub crypto.PublicKey // public key for client auth, if any
477
478 msg, err := c.readHandshake()
479 if err != nil {
480 return err
481 }
482
483 var ok bool
484 // If we requested a client certificate, then the client must send a
485 // certificate message, even if it's empty.
486 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -0400487 var certMsg *certificateMsg
Adam Langley95c29f32014-06-20 12:00:00 -0700488 if certMsg, ok = msg.(*certificateMsg); !ok {
489 c.sendAlert(alertUnexpectedMessage)
490 return unexpectedMessageError(certMsg, msg)
491 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400492 hs.writeClientHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700493
494 if len(certMsg.certificates) == 0 {
495 // The client didn't actually send a certificate
496 switch config.ClientAuth {
497 case RequireAnyClientCert, RequireAndVerifyClientCert:
498 c.sendAlert(alertBadCertificate)
499 return errors.New("tls: client didn't provide a certificate")
500 }
501 }
502
503 pub, err = hs.processCertsFromClient(certMsg.certificates)
504 if err != nil {
505 return err
506 }
507
508 msg, err = c.readHandshake()
509 if err != nil {
510 return err
511 }
512 }
513
514 // Get client key exchange
515 ckx, ok := msg.(*clientKeyExchangeMsg)
516 if !ok {
517 c.sendAlert(alertUnexpectedMessage)
518 return unexpectedMessageError(ckx, msg)
519 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400520 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700521
David Benjamine098ec22014-08-27 23:13:20 -0400522 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
523 if err != nil {
524 c.sendAlert(alertHandshakeFailure)
525 return err
526 }
Adam Langley75712922014-10-10 16:23:43 -0700527 if c.extendedMasterSecret {
528 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
529 } else {
530 if c.config.Bugs.RequireExtendedMasterSecret {
531 return errors.New("tls: extended master secret required but not supported by peer")
532 }
533 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
534 }
David Benjamine098ec22014-08-27 23:13:20 -0400535
Adam Langley95c29f32014-06-20 12:00:00 -0700536 // If we received a client cert in response to our certificate request message,
537 // the client will send us a certificateVerifyMsg immediately after the
538 // clientKeyExchangeMsg. This message is a digest of all preceding
539 // handshake-layer messages that is signed using the private key corresponding
540 // to the client's certificate. This allows us to verify that the client is in
541 // possession of the private key of the certificate.
542 if len(c.peerCertificates) > 0 {
543 msg, err = c.readHandshake()
544 if err != nil {
545 return err
546 }
547 certVerify, ok := msg.(*certificateVerifyMsg)
548 if !ok {
549 c.sendAlert(alertUnexpectedMessage)
550 return unexpectedMessageError(certVerify, msg)
551 }
552
David Benjaminde620d92014-07-18 15:03:41 -0400553 // Determine the signature type.
554 var signatureAndHash signatureAndHash
555 if certVerify.hasSignatureAndHash {
556 signatureAndHash = certVerify.signatureAndHash
557 } else {
558 // Before TLS 1.2 the signature algorithm was implicit
559 // from the key type, and only one hash per signature
560 // algorithm was possible. Leave the hash as zero.
561 switch pub.(type) {
562 case *ecdsa.PublicKey:
563 signatureAndHash.signature = signatureECDSA
564 case *rsa.PublicKey:
565 signatureAndHash.signature = signatureRSA
566 }
567 }
568
Adam Langley95c29f32014-06-20 12:00:00 -0700569 switch key := pub.(type) {
570 case *ecdsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400571 if signatureAndHash.signature != signatureECDSA {
572 err = errors.New("tls: bad signature type for client's ECDSA certificate")
573 break
574 }
Adam Langley95c29f32014-06-20 12:00:00 -0700575 ecdsaSig := new(ecdsaSignature)
576 if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {
577 break
578 }
579 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
580 err = errors.New("ECDSA signature contained zero or negative values")
581 break
582 }
David Benjaminde620d92014-07-18 15:03:41 -0400583 var digest []byte
David Benjamine098ec22014-08-27 23:13:20 -0400584 digest, _, 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 if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {
589 err = errors.New("ECDSA verification failure")
590 break
591 }
592 case *rsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400593 if signatureAndHash.signature != signatureRSA {
594 err = errors.New("tls: bad signature type for client's RSA certificate")
595 break
596 }
597 var digest []byte
598 var hashFunc crypto.Hash
David Benjamine098ec22014-08-27 23:13:20 -0400599 digest, hashFunc, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400600 if err != nil {
601 break
602 }
Adam Langley95c29f32014-06-20 12:00:00 -0700603 err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)
604 }
605 if err != nil {
606 c.sendAlert(alertBadCertificate)
607 return errors.New("could not validate signature of connection nonces: " + err.Error())
608 }
609
David Benjamin83c0bc92014-08-04 01:23:53 -0400610 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700611 }
612
David Benjamine098ec22014-08-27 23:13:20 -0400613 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -0700614
615 return nil
616}
617
618func (hs *serverHandshakeState) establishKeys() error {
619 c := hs.c
620
621 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
622 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
623
624 var clientCipher, serverCipher interface{}
625 var clientHash, serverHash macFunction
626
627 if hs.suite.aead == nil {
628 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
629 clientHash = hs.suite.mac(c.vers, clientMAC)
630 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
631 serverHash = hs.suite.mac(c.vers, serverMAC)
632 } else {
633 clientCipher = hs.suite.aead(clientKey, clientIV)
634 serverCipher = hs.suite.aead(serverKey, serverIV)
635 }
636
637 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
638 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
639
640 return nil
641}
642
David Benjamind30a9902014-08-24 01:44:23 -0400643func (hs *serverHandshakeState) readFinished(isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700644 c := hs.c
645
646 c.readRecord(recordTypeChangeCipherSpec)
647 if err := c.in.error(); err != nil {
648 return err
649 }
650
651 if hs.hello.nextProtoNeg {
652 msg, err := c.readHandshake()
653 if err != nil {
654 return err
655 }
656 nextProto, ok := msg.(*nextProtoMsg)
657 if !ok {
658 c.sendAlert(alertUnexpectedMessage)
659 return unexpectedMessageError(nextProto, msg)
660 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400661 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700662 c.clientProtocol = nextProto.proto
663 }
664
David Benjamind30a9902014-08-24 01:44:23 -0400665 if hs.hello.channelIDRequested {
666 msg, err := c.readHandshake()
667 if err != nil {
668 return err
669 }
670 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
671 if !ok {
672 c.sendAlert(alertUnexpectedMessage)
673 return unexpectedMessageError(encryptedExtensions, msg)
674 }
675 x := new(big.Int).SetBytes(encryptedExtensions.channelID[0:32])
676 y := new(big.Int).SetBytes(encryptedExtensions.channelID[32:64])
677 r := new(big.Int).SetBytes(encryptedExtensions.channelID[64:96])
678 s := new(big.Int).SetBytes(encryptedExtensions.channelID[96:128])
679 if !elliptic.P256().IsOnCurve(x, y) {
680 return errors.New("tls: invalid channel ID public key")
681 }
682 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
683 var resumeHash []byte
684 if isResume {
685 resumeHash = hs.sessionState.handshakeHash
686 }
687 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
688 return errors.New("tls: invalid channel ID signature")
689 }
690 c.channelID = channelID
691
692 hs.writeClientHash(encryptedExtensions.marshal())
693 }
694
Adam Langley95c29f32014-06-20 12:00:00 -0700695 msg, err := c.readHandshake()
696 if err != nil {
697 return err
698 }
699 clientFinished, ok := msg.(*finishedMsg)
700 if !ok {
701 c.sendAlert(alertUnexpectedMessage)
702 return unexpectedMessageError(clientFinished, msg)
703 }
704
705 verify := hs.finishedHash.clientSum(hs.masterSecret)
706 if len(verify) != len(clientFinished.verifyData) ||
707 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
708 c.sendAlert(alertHandshakeFailure)
709 return errors.New("tls: client's Finished message is incorrect")
710 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700711 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langley95c29f32014-06-20 12:00:00 -0700712
David Benjamin83c0bc92014-08-04 01:23:53 -0400713 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700714 return nil
715}
716
717func (hs *serverHandshakeState) sendSessionTicket() error {
David Benjamind23f4122014-07-23 15:09:48 -0400718 if !hs.hello.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
Adam Langley95c29f32014-06-20 12:00:00 -0700719 return nil
720 }
721
722 c := hs.c
723 m := new(newSessionTicketMsg)
724
725 var err error
726 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -0400727 vers: c.vers,
728 cipherSuite: hs.suite.id,
729 masterSecret: hs.masterSecret,
730 certificates: hs.certsFromClient,
731 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -0700732 }
733 m.ticket, err = c.encryptTicket(&state)
734 if err != nil {
735 return err
736 }
Adam Langley95c29f32014-06-20 12:00:00 -0700737
David Benjamin83c0bc92014-08-04 01:23:53 -0400738 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700739 c.writeRecord(recordTypeHandshake, m.marshal())
740
741 return nil
742}
743
744func (hs *serverHandshakeState) sendFinished() error {
745 c := hs.c
746
David Benjamin86271ee2014-07-21 16:14:03 -0400747 finished := new(finishedMsg)
748 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
Adam Langley2ae77d22014-10-28 17:29:33 -0700749 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin86271ee2014-07-21 16:14:03 -0400750 postCCSBytes := finished.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -0400751 hs.writeServerHash(postCCSBytes)
David Benjamin86271ee2014-07-21 16:14:03 -0400752
753 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
754 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
755 postCCSBytes = postCCSBytes[5:]
756 }
757
David Benjamina0e52232014-07-19 17:39:58 -0400758 if !c.config.Bugs.SkipChangeCipherSpec {
759 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
760 }
Adam Langley95c29f32014-06-20 12:00:00 -0700761
David Benjamin86271ee2014-07-21 16:14:03 -0400762 c.writeRecord(recordTypeHandshake, postCCSBytes)
Adam Langley95c29f32014-06-20 12:00:00 -0700763
764 c.cipherSuite = hs.suite.id
765
766 return nil
767}
768
769// processCertsFromClient takes a chain of client certificates either from a
770// Certificates message or from a sessionState and verifies them. It returns
771// the public key of the leaf certificate.
772func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
773 c := hs.c
774
775 hs.certsFromClient = certificates
776 certs := make([]*x509.Certificate, len(certificates))
777 var err error
778 for i, asn1Data := range certificates {
779 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
780 c.sendAlert(alertBadCertificate)
781 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
782 }
783 }
784
785 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
786 opts := x509.VerifyOptions{
787 Roots: c.config.ClientCAs,
788 CurrentTime: c.config.time(),
789 Intermediates: x509.NewCertPool(),
790 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
791 }
792
793 for _, cert := range certs[1:] {
794 opts.Intermediates.AddCert(cert)
795 }
796
797 chains, err := certs[0].Verify(opts)
798 if err != nil {
799 c.sendAlert(alertBadCertificate)
800 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
801 }
802
803 ok := false
804 for _, ku := range certs[0].ExtKeyUsage {
805 if ku == x509.ExtKeyUsageClientAuth {
806 ok = true
807 break
808 }
809 }
810 if !ok {
811 c.sendAlert(alertHandshakeFailure)
812 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
813 }
814
815 c.verifiedChains = chains
816 }
817
818 if len(certs) > 0 {
819 var pub crypto.PublicKey
820 switch key := certs[0].PublicKey.(type) {
821 case *ecdsa.PublicKey, *rsa.PublicKey:
822 pub = key
823 default:
824 c.sendAlert(alertUnsupportedCertificate)
825 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
826 }
827 c.peerCertificates = certs
828 return pub, nil
829 }
830
831 return nil, nil
832}
833
David Benjamin83c0bc92014-08-04 01:23:53 -0400834func (hs *serverHandshakeState) writeServerHash(msg []byte) {
835 // writeServerHash is called before writeRecord.
836 hs.writeHash(msg, hs.c.sendHandshakeSeq)
837}
838
839func (hs *serverHandshakeState) writeClientHash(msg []byte) {
840 // writeClientHash is called after readHandshake.
841 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
842}
843
844func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
845 if hs.c.isDTLS {
846 // This is somewhat hacky. DTLS hashes a slightly different format.
847 // First, the TLS header.
848 hs.finishedHash.Write(msg[:4])
849 // Then the sequence number and reassembled fragment offset (always 0).
850 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
851 // Then the reassembled fragment (always equal to the message length).
852 hs.finishedHash.Write(msg[1:4])
853 // And then the message body.
854 hs.finishedHash.Write(msg[4:])
855 } else {
856 hs.finishedHash.Write(msg)
857 }
858}
859
Adam Langley95c29f32014-06-20 12:00:00 -0700860// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
861// is acceptable to use.
862func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
863 for _, supported := range supportedCipherSuites {
864 if id == supported {
865 var candidate *cipherSuite
866
867 for _, s := range cipherSuites {
868 if s.id == id {
869 candidate = s
870 break
871 }
872 }
873 if candidate == nil {
874 continue
875 }
876 // Don't select a ciphersuite which we can't
877 // support for this client.
878 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
879 continue
880 }
881 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
882 continue
883 }
David Benjamin39ebf532014-08-31 02:23:49 -0400884 if !c.config.Bugs.SkipCipherVersionCheck && version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700885 continue
886 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400887 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
888 continue
889 }
Adam Langley95c29f32014-06-20 12:00:00 -0700890 return candidate
891 }
892 }
893
894 return nil
895}