blob: e1d49e5fb9b369f57904b62619bfbc44670297bb [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
David Benjamin83f90402015-01-27 01:09:43 -050036 finishedBytes []byte
Adam Langley95c29f32014-06-20 12:00:00 -070037}
38
39// serverHandshake performs a TLS handshake as a server.
40func (c *Conn) serverHandshake() error {
41 config := c.config
42
43 // If this is the first server handshake, we generate a random key to
44 // encrypt the tickets with.
45 config.serverInitOnce.Do(config.serverInit)
46
David Benjamin83c0bc92014-08-04 01:23:53 -040047 c.sendHandshakeSeq = 0
48 c.recvHandshakeSeq = 0
49
Adam Langley95c29f32014-06-20 12:00:00 -070050 hs := serverHandshakeState{
51 c: c,
52 }
53 isResume, err := hs.readClientHello()
54 if err != nil {
55 return err
56 }
57
58 // For an overview of TLS handshaking, see https://tools.ietf.org/html/rfc5246#section-7.3
59 if isResume {
60 // The client has included a session ticket and so we do an abbreviated handshake.
61 if err := hs.doResumeHandshake(); err != nil {
62 return err
63 }
64 if err := hs.establishKeys(); err != nil {
65 return err
66 }
David Benjaminbed9aae2014-08-07 19:13:38 -040067 if c.config.Bugs.RenewTicketOnResume {
68 if err := hs.sendSessionTicket(); err != nil {
69 return err
70 }
71 }
Adam Langley95c29f32014-06-20 12:00:00 -070072 if err := hs.sendFinished(); err != nil {
73 return err
74 }
David Benjamin83f90402015-01-27 01:09:43 -050075 // Most retransmits are triggered by a timeout, but the final
76 // leg of the handshake is retransmited upon re-receiving a
77 // Finished.
David Benjaminb3774b92015-01-31 17:16:01 -050078 if err := c.simulatePacketLoss(func() {
79 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
David Benjamina4e6d482015-03-02 19:10:53 -050080 c.dtlsFlushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -050081 }); err != nil {
David Benjamin83f90402015-01-27 01:09:43 -050082 return err
83 }
David Benjamind30a9902014-08-24 01:44:23 -040084 if err := hs.readFinished(isResume); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -070085 return err
86 }
87 c.didResume = true
88 } else {
89 // The client didn't include a session ticket, or it wasn't
90 // valid so we do a full handshake.
91 if err := hs.doFullHandshake(); err != nil {
92 return err
93 }
94 if err := hs.establishKeys(); err != nil {
95 return err
96 }
David Benjamind30a9902014-08-24 01:44:23 -040097 if err := hs.readFinished(isResume); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -070098 return err
99 }
David Benjamine58c4f52014-08-24 03:47:07 -0400100 if c.config.Bugs.ExpectFalseStart {
101 if err := c.readRecord(recordTypeApplicationData); err != nil {
102 return err
103 }
104 }
Adam Langley95c29f32014-06-20 12:00:00 -0700105 if err := hs.sendSessionTicket(); err != nil {
106 return err
107 }
108 if err := hs.sendFinished(); err != nil {
109 return err
110 }
111 }
112 c.handshakeComplete = true
113
114 return nil
115}
116
117// readClientHello reads a ClientHello message from the client and decides
118// whether we will perform session resumption.
119func (hs *serverHandshakeState) readClientHello() (isResume bool, err error) {
120 config := hs.c.config
121 c := hs.c
122
David Benjamin83f90402015-01-27 01:09:43 -0500123 if err := c.simulatePacketLoss(nil); err != nil {
124 return false, err
125 }
Adam Langley95c29f32014-06-20 12:00:00 -0700126 msg, err := c.readHandshake()
127 if err != nil {
128 return false, err
129 }
130 var ok bool
131 hs.clientHello, ok = msg.(*clientHelloMsg)
132 if !ok {
133 c.sendAlert(alertUnexpectedMessage)
134 return false, unexpectedMessageError(hs.clientHello, msg)
135 }
Feng Lu41aa3252014-11-21 22:47:56 -0800136 if config.Bugs.RequireFastradioPadding && len(hs.clientHello.raw) < 1000 {
137 return false, errors.New("tls: ClientHello record size should be larger than 1000 bytes when padding enabled.")
138 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400139
140 if c.isDTLS && !config.Bugs.SkipHelloVerifyRequest {
David Benjamin8bc38f52014-08-16 12:07:27 -0400141 // Per RFC 6347, the version field in HelloVerifyRequest SHOULD
142 // be always DTLS 1.0
David Benjamin83c0bc92014-08-04 01:23:53 -0400143 helloVerifyRequest := &helloVerifyRequestMsg{
David Benjamin8bc38f52014-08-16 12:07:27 -0400144 vers: VersionTLS10,
David Benjamin83c0bc92014-08-04 01:23:53 -0400145 cookie: make([]byte, 32),
146 }
147 if _, err := io.ReadFull(c.config.rand(), helloVerifyRequest.cookie); err != nil {
148 c.sendAlert(alertInternalError)
149 return false, errors.New("dtls: short read from Rand: " + err.Error())
150 }
151 c.writeRecord(recordTypeHandshake, helloVerifyRequest.marshal())
David Benjamina4e6d482015-03-02 19:10:53 -0500152 c.dtlsFlushHandshake()
David Benjamin83c0bc92014-08-04 01:23:53 -0400153
David Benjamin83f90402015-01-27 01:09:43 -0500154 if err := c.simulatePacketLoss(nil); err != nil {
155 return false, err
156 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400157 msg, err := c.readHandshake()
158 if err != nil {
159 return false, err
160 }
161 newClientHello, ok := msg.(*clientHelloMsg)
162 if !ok {
163 c.sendAlert(alertUnexpectedMessage)
164 return false, unexpectedMessageError(hs.clientHello, msg)
165 }
166 if !bytes.Equal(newClientHello.cookie, helloVerifyRequest.cookie) {
167 return false, errors.New("dtls: invalid cookie")
168 }
David Benjaminf2fedef2014-08-16 01:37:34 -0400169
170 // Apart from the cookie, the two ClientHellos must
171 // match. Note that clientHello.equal compares the
172 // serialization, so we make a copy.
173 oldClientHelloCopy := *hs.clientHello
174 oldClientHelloCopy.raw = nil
175 oldClientHelloCopy.cookie = nil
176 newClientHelloCopy := *newClientHello
177 newClientHelloCopy.raw = nil
178 newClientHelloCopy.cookie = nil
179 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400180 return false, errors.New("dtls: retransmitted ClientHello does not match")
181 }
182 hs.clientHello = newClientHello
183 }
184
David Benjaminc44b1df2014-11-23 12:11:01 -0500185 if config.Bugs.RequireSameRenegoClientVersion && c.clientVersion != 0 {
186 if c.clientVersion != hs.clientHello.vers {
187 return false, fmt.Errorf("tls: client offered different version on renego")
188 }
189 }
190 c.clientVersion = hs.clientHello.vers
191
David Benjamin6ae7f072015-01-26 10:22:13 -0500192 // Reject < 1.2 ClientHellos with signature_algorithms.
193 if c.clientVersion < VersionTLS12 && len(hs.clientHello.signatureAndHashes) > 0 {
194 return false, fmt.Errorf("tls: client included signature_algorithms before TLS 1.2")
195 }
196
David Benjamin8bc38f52014-08-16 12:07:27 -0400197 c.vers, ok = config.mutualVersion(hs.clientHello.vers)
198 if !ok {
199 c.sendAlert(alertProtocolVersion)
200 return false, fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
201 }
Adam Langley95c29f32014-06-20 12:00:00 -0700202 c.haveVers = true
203
204 hs.hello = new(serverHelloMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400205 hs.hello.isDTLS = c.isDTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700206
207 supportedCurve := false
208 preferredCurves := config.curvePreferences()
209Curves:
210 for _, curve := range hs.clientHello.supportedCurves {
211 for _, supported := range preferredCurves {
212 if supported == curve {
213 supportedCurve = true
214 break Curves
215 }
216 }
217 }
218
219 supportedPointFormat := false
220 for _, pointFormat := range hs.clientHello.supportedPoints {
221 if pointFormat == pointFormatUncompressed {
222 supportedPointFormat = true
223 break
224 }
225 }
226 hs.ellipticOk = supportedCurve && supportedPointFormat
227
228 foundCompression := false
229 // We only support null compression, so check that the client offered it.
230 for _, compression := range hs.clientHello.compressionMethods {
231 if compression == compressionNone {
232 foundCompression = true
233 break
234 }
235 }
236
237 if !foundCompression {
238 c.sendAlert(alertHandshakeFailure)
239 return false, errors.New("tls: client does not support uncompressed connections")
240 }
241
242 hs.hello.vers = c.vers
243 hs.hello.random = make([]byte, 32)
244 _, err = io.ReadFull(config.rand(), hs.hello.random)
245 if err != nil {
246 c.sendAlert(alertInternalError)
247 return false, err
248 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700249
Adam Langleycf2d4f42014-10-28 19:06:14 -0700250 if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) {
Adam Langley2ae77d22014-10-28 17:29:33 -0700251 c.sendAlert(alertHandshakeFailure)
Adam Langleycf2d4f42014-10-28 19:06:14 -0700252 return false, errors.New("tls: renegotiation mismatch")
Adam Langley2ae77d22014-10-28 17:29:33 -0700253 }
Adam Langleycf2d4f42014-10-28 19:06:14 -0700254
255 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
256 hs.hello.secureRenegotiation = append(hs.hello.secureRenegotiation, c.clientVerify...)
257 hs.hello.secureRenegotiation = append(hs.hello.secureRenegotiation, c.serverVerify...)
258 if c.config.Bugs.BadRenegotiationInfo {
259 hs.hello.secureRenegotiation[0] ^= 0x80
260 }
261 } else {
262 hs.hello.secureRenegotiation = hs.clientHello.secureRenegotiation
263 }
264
Adam Langley95c29f32014-06-20 12:00:00 -0700265 hs.hello.compressionMethod = compressionNone
David Benjamin35a7a442014-07-05 00:23:20 -0400266 hs.hello.duplicateExtension = c.config.Bugs.DuplicateExtension
Adam Langley95c29f32014-06-20 12:00:00 -0700267 if len(hs.clientHello.serverName) > 0 {
268 c.serverName = hs.clientHello.serverName
269 }
David Benjaminfa055a22014-09-15 16:51:51 -0400270
271 if len(hs.clientHello.alpnProtocols) > 0 {
272 if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
273 hs.hello.alpnProtocol = selectedProto
274 c.clientProtocol = selectedProto
David Benjaminfc7b0862014-09-06 13:21:53 -0400275 c.usedALPN = true
David Benjaminfa055a22014-09-15 16:51:51 -0400276 }
277 } else {
278 // Although sending an empty NPN extension is reasonable, Firefox has
279 // had a bug around this. Best to send nothing at all if
280 // config.NextProtos is empty. See
281 // https://code.google.com/p/go/issues/detail?id=5445.
282 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
283 hs.hello.nextProtoNeg = true
284 hs.hello.nextProtos = config.NextProtos
285 }
Adam Langley95c29f32014-06-20 12:00:00 -0700286 }
Adam Langley75712922014-10-10 16:23:43 -0700287 hs.hello.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !c.config.Bugs.NoExtendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700288
289 if len(config.Certificates) == 0 {
290 c.sendAlert(alertInternalError)
291 return false, errors.New("tls: no certificates configured")
292 }
293 hs.cert = &config.Certificates[0]
294 if len(hs.clientHello.serverName) > 0 {
295 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
296 }
David Benjamine78bfde2014-09-06 12:45:15 -0400297 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
298 return false, errors.New("tls: unexpected server name")
299 }
Adam Langley95c29f32014-06-20 12:00:00 -0700300
David Benjamind30a9902014-08-24 01:44:23 -0400301 if hs.clientHello.channelIDSupported && config.RequestChannelID {
302 hs.hello.channelIDRequested = true
303 }
304
David Benjaminca6c8262014-11-15 19:06:08 -0500305 if hs.clientHello.srtpProtectionProfiles != nil {
306 SRTPLoop:
307 for _, p1 := range c.config.SRTPProtectionProfiles {
308 for _, p2 := range hs.clientHello.srtpProtectionProfiles {
309 if p1 == p2 {
310 hs.hello.srtpProtectionProfile = p1
311 c.srtpProtectionProfile = p1
312 break SRTPLoop
313 }
314 }
315 }
316 }
317
318 if c.config.Bugs.SendSRTPProtectionProfile != 0 {
319 hs.hello.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
320 }
321
Adam Langley95c29f32014-06-20 12:00:00 -0700322 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
323
324 if hs.checkForResumption() {
325 return true, nil
326 }
327
Adam Langleyac61fa32014-06-23 12:03:11 -0700328 var scsvFound bool
329
330 for _, cipherSuite := range hs.clientHello.cipherSuites {
331 if cipherSuite == fallbackSCSV {
332 scsvFound = true
333 break
334 }
335 }
336
337 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
338 return false, errors.New("tls: no fallback SCSV found when expected")
339 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
340 return false, errors.New("tls: fallback SCSV found when not expected")
341 }
342
Adam Langley95c29f32014-06-20 12:00:00 -0700343 var preferenceList, supportedList []uint16
344 if c.config.PreferServerCipherSuites {
345 preferenceList = c.config.cipherSuites()
346 supportedList = hs.clientHello.cipherSuites
347 } else {
348 preferenceList = hs.clientHello.cipherSuites
349 supportedList = c.config.cipherSuites()
350 }
351
352 for _, id := range preferenceList {
353 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
354 break
355 }
356 }
357
358 if hs.suite == nil {
359 c.sendAlert(alertHandshakeFailure)
360 return false, errors.New("tls: no cipher suite supported by both client and server")
361 }
362
363 return false, nil
364}
365
366// checkForResumption returns true if we should perform resumption on this connection.
367func (hs *serverHandshakeState) checkForResumption() bool {
368 c := hs.c
369
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500370 if len(hs.clientHello.sessionTicket) > 0 {
371 if c.config.SessionTicketsDisabled {
372 return false
373 }
David Benjaminb0c8db72014-09-24 15:19:56 -0400374
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500375 var ok bool
376 if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
377 return false
378 }
379 } else {
380 if c.config.ServerSessionCache == nil {
381 return false
382 }
383
384 var ok bool
385 sessionId := string(hs.clientHello.sessionId)
386 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
387 return false
388 }
Adam Langley95c29f32014-06-20 12:00:00 -0700389 }
390
David Benjamine18d8212014-11-10 02:37:15 -0500391 // Never resume a session for a different SSL version.
392 if !c.config.Bugs.AllowSessionVersionMismatch && c.vers != hs.sessionState.vers {
393 return false
Adam Langley95c29f32014-06-20 12:00:00 -0700394 }
395
396 cipherSuiteOk := false
397 // Check that the client is still offering the ciphersuite in the session.
398 for _, id := range hs.clientHello.cipherSuites {
399 if id == hs.sessionState.cipherSuite {
400 cipherSuiteOk = true
401 break
402 }
403 }
404 if !cipherSuiteOk {
405 return false
406 }
407
408 // Check that we also support the ciphersuite from the session.
409 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk)
410 if hs.suite == nil {
411 return false
412 }
413
414 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
415 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
416 if needClientCerts && !sessionHasClientCerts {
417 return false
418 }
419 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
420 return false
421 }
422
423 return true
424}
425
426func (hs *serverHandshakeState) doResumeHandshake() error {
427 c := hs.c
428
429 hs.hello.cipherSuite = hs.suite.id
430 // We echo the client's session ID in the ServerHello to let it know
431 // that we're doing a resumption.
432 hs.hello.sessionId = hs.clientHello.sessionId
David Benjaminbed9aae2014-08-07 19:13:38 -0400433 hs.hello.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -0700434
435 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -0400436 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -0400437 hs.writeClientHash(hs.clientHello.marshal())
438 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700439
440 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
441
442 if len(hs.sessionState.certificates) > 0 {
443 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
444 return err
445 }
446 }
447
448 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -0700449 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700450
451 return nil
452}
453
454func (hs *serverHandshakeState) doFullHandshake() error {
455 config := hs.c.config
456 c := hs.c
457
David Benjamin48cae082014-10-27 01:06:24 -0400458 isPSK := hs.suite.flags&suitePSK != 0
459 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700460 hs.hello.ocspStapling = true
461 }
462
David Benjamin61f95272014-11-25 01:55:35 -0500463 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
464 hs.hello.sctList = hs.cert.SignedCertificateTimestampList
465 }
466
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500467 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
Adam Langley95c29f32014-06-20 12:00:00 -0700468 hs.hello.cipherSuite = hs.suite.id
David Benjamin6095de82014-12-27 01:50:38 -0500469 if config.Bugs.SendCipherSuite != 0 {
470 hs.hello.cipherSuite = config.Bugs.SendCipherSuite
471 }
Adam Langley75712922014-10-10 16:23:43 -0700472 c.extendedMasterSecret = hs.hello.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700473
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500474 // Generate a session ID if we're to save the session.
475 if !hs.hello.ticketSupported && config.ServerSessionCache != nil {
476 hs.hello.sessionId = make([]byte, 32)
477 if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
478 c.sendAlert(alertInternalError)
479 return errors.New("tls: short read from Rand: " + err.Error())
480 }
481 }
482
Adam Langley95c29f32014-06-20 12:00:00 -0700483 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400484 hs.writeClientHash(hs.clientHello.marshal())
485 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700486
487 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
488
David Benjamin48cae082014-10-27 01:06:24 -0400489 if !isPSK {
490 certMsg := new(certificateMsg)
491 certMsg.certificates = hs.cert.Certificate
492 if !config.Bugs.UnauthenticatedECDH {
David Benjaminbcb2d912015-02-24 23:45:43 -0500493 certMsgBytes := certMsg.marshal()
494 if config.Bugs.WrongCertificateMessageType {
495 certMsgBytes[0] += 42
496 }
497 hs.writeServerHash(certMsgBytes)
498 c.writeRecord(recordTypeHandshake, certMsgBytes)
David Benjamin48cae082014-10-27 01:06:24 -0400499 }
David Benjamin1c375dd2014-07-12 00:48:23 -0400500 }
Adam Langley95c29f32014-06-20 12:00:00 -0700501
502 if hs.hello.ocspStapling {
503 certStatus := new(certificateStatusMsg)
504 certStatus.statusType = statusTypeOCSP
505 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -0400506 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700507 c.writeRecord(recordTypeHandshake, certStatus.marshal())
508 }
509
510 keyAgreement := hs.suite.ka(c.vers)
511 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
512 if err != nil {
513 c.sendAlert(alertHandshakeFailure)
514 return err
515 }
David Benjamin9c651c92014-07-12 13:27:45 -0400516 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -0400517 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700518 c.writeRecord(recordTypeHandshake, skx.marshal())
519 }
520
521 if config.ClientAuth >= RequestClientCert {
522 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -0400523 certReq := &certificateRequestMsg{
524 certificateTypes: config.ClientCertificateTypes,
525 }
526 if certReq.certificateTypes == nil {
527 certReq.certificateTypes = []byte{
528 byte(CertTypeRSASign),
529 byte(CertTypeECDSASign),
530 }
Adam Langley95c29f32014-06-20 12:00:00 -0700531 }
532 if c.vers >= VersionTLS12 {
533 certReq.hasSignatureAndHash = true
David Benjamin000800a2014-11-14 01:43:59 -0500534 if !config.Bugs.NoSignatureAndHashes {
535 certReq.signatureAndHashes = config.signatureAndHashesForServer()
536 }
Adam Langley95c29f32014-06-20 12:00:00 -0700537 }
538
539 // An empty list of certificateAuthorities signals to
540 // the client that it may send any certificate in response
541 // to our request. When we know the CAs we trust, then
542 // we can send them down, so that the client can choose
543 // an appropriate certificate to give to us.
544 if config.ClientCAs != nil {
545 certReq.certificateAuthorities = config.ClientCAs.Subjects()
546 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400547 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700548 c.writeRecord(recordTypeHandshake, certReq.marshal())
549 }
550
551 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400552 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700553 c.writeRecord(recordTypeHandshake, helloDone.marshal())
David Benjamina4e6d482015-03-02 19:10:53 -0500554 c.dtlsFlushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700555
556 var pub crypto.PublicKey // public key for client auth, if any
557
David Benjamin83f90402015-01-27 01:09:43 -0500558 if err := c.simulatePacketLoss(nil); err != nil {
559 return err
560 }
Adam Langley95c29f32014-06-20 12:00:00 -0700561 msg, err := c.readHandshake()
562 if err != nil {
563 return err
564 }
565
566 var ok bool
567 // If we requested a client certificate, then the client must send a
568 // certificate message, even if it's empty.
569 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -0400570 var certMsg *certificateMsg
Adam Langley95c29f32014-06-20 12:00:00 -0700571 if certMsg, ok = msg.(*certificateMsg); !ok {
572 c.sendAlert(alertUnexpectedMessage)
573 return unexpectedMessageError(certMsg, msg)
574 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400575 hs.writeClientHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700576
577 if len(certMsg.certificates) == 0 {
578 // The client didn't actually send a certificate
579 switch config.ClientAuth {
580 case RequireAnyClientCert, RequireAndVerifyClientCert:
581 c.sendAlert(alertBadCertificate)
582 return errors.New("tls: client didn't provide a certificate")
583 }
584 }
585
586 pub, err = hs.processCertsFromClient(certMsg.certificates)
587 if err != nil {
588 return err
589 }
590
591 msg, err = c.readHandshake()
592 if err != nil {
593 return err
594 }
595 }
596
597 // Get client key exchange
598 ckx, ok := msg.(*clientKeyExchangeMsg)
599 if !ok {
600 c.sendAlert(alertUnexpectedMessage)
601 return unexpectedMessageError(ckx, msg)
602 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400603 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700604
David Benjamine098ec22014-08-27 23:13:20 -0400605 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
606 if err != nil {
607 c.sendAlert(alertHandshakeFailure)
608 return err
609 }
Adam Langley75712922014-10-10 16:23:43 -0700610 if c.extendedMasterSecret {
611 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
612 } else {
613 if c.config.Bugs.RequireExtendedMasterSecret {
614 return errors.New("tls: extended master secret required but not supported by peer")
615 }
616 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
617 }
David Benjamine098ec22014-08-27 23:13:20 -0400618
Adam Langley95c29f32014-06-20 12:00:00 -0700619 // If we received a client cert in response to our certificate request message,
620 // the client will send us a certificateVerifyMsg immediately after the
621 // clientKeyExchangeMsg. This message is a digest of all preceding
622 // handshake-layer messages that is signed using the private key corresponding
623 // to the client's certificate. This allows us to verify that the client is in
624 // possession of the private key of the certificate.
625 if len(c.peerCertificates) > 0 {
626 msg, err = c.readHandshake()
627 if err != nil {
628 return err
629 }
630 certVerify, ok := msg.(*certificateVerifyMsg)
631 if !ok {
632 c.sendAlert(alertUnexpectedMessage)
633 return unexpectedMessageError(certVerify, msg)
634 }
635
David Benjaminde620d92014-07-18 15:03:41 -0400636 // Determine the signature type.
637 var signatureAndHash signatureAndHash
638 if certVerify.hasSignatureAndHash {
639 signatureAndHash = certVerify.signatureAndHash
David Benjamin000800a2014-11-14 01:43:59 -0500640 if !isSupportedSignatureAndHash(signatureAndHash, config.signatureAndHashesForServer()) {
641 return errors.New("tls: unsupported hash function for client certificate")
642 }
David Benjaminde620d92014-07-18 15:03:41 -0400643 } else {
644 // Before TLS 1.2 the signature algorithm was implicit
645 // from the key type, and only one hash per signature
646 // algorithm was possible. Leave the hash as zero.
647 switch pub.(type) {
648 case *ecdsa.PublicKey:
649 signatureAndHash.signature = signatureECDSA
650 case *rsa.PublicKey:
651 signatureAndHash.signature = signatureRSA
652 }
653 }
654
Adam Langley95c29f32014-06-20 12:00:00 -0700655 switch key := pub.(type) {
656 case *ecdsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400657 if signatureAndHash.signature != signatureECDSA {
658 err = errors.New("tls: bad signature type for client's ECDSA certificate")
659 break
660 }
Adam Langley95c29f32014-06-20 12:00:00 -0700661 ecdsaSig := new(ecdsaSignature)
662 if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {
663 break
664 }
665 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
666 err = errors.New("ECDSA signature contained zero or negative values")
667 break
668 }
David Benjaminde620d92014-07-18 15:03:41 -0400669 var digest []byte
David Benjamine098ec22014-08-27 23:13:20 -0400670 digest, _, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400671 if err != nil {
672 break
673 }
Adam Langley95c29f32014-06-20 12:00:00 -0700674 if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {
675 err = errors.New("ECDSA verification failure")
676 break
677 }
678 case *rsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400679 if signatureAndHash.signature != signatureRSA {
680 err = errors.New("tls: bad signature type for client's RSA certificate")
681 break
682 }
683 var digest []byte
684 var hashFunc crypto.Hash
David Benjamine098ec22014-08-27 23:13:20 -0400685 digest, hashFunc, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400686 if err != nil {
687 break
688 }
Adam Langley95c29f32014-06-20 12:00:00 -0700689 err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)
690 }
691 if err != nil {
692 c.sendAlert(alertBadCertificate)
693 return errors.New("could not validate signature of connection nonces: " + err.Error())
694 }
695
David Benjamin83c0bc92014-08-04 01:23:53 -0400696 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700697 }
698
David Benjamine098ec22014-08-27 23:13:20 -0400699 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -0700700
701 return nil
702}
703
704func (hs *serverHandshakeState) establishKeys() error {
705 c := hs.c
706
707 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
708 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
709
710 var clientCipher, serverCipher interface{}
711 var clientHash, serverHash macFunction
712
713 if hs.suite.aead == nil {
714 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
715 clientHash = hs.suite.mac(c.vers, clientMAC)
716 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
717 serverHash = hs.suite.mac(c.vers, serverMAC)
718 } else {
719 clientCipher = hs.suite.aead(clientKey, clientIV)
720 serverCipher = hs.suite.aead(serverKey, serverIV)
721 }
722
723 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
724 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
725
726 return nil
727}
728
David Benjamind30a9902014-08-24 01:44:23 -0400729func (hs *serverHandshakeState) readFinished(isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700730 c := hs.c
731
732 c.readRecord(recordTypeChangeCipherSpec)
733 if err := c.in.error(); err != nil {
734 return err
735 }
736
737 if hs.hello.nextProtoNeg {
738 msg, err := c.readHandshake()
739 if err != nil {
740 return err
741 }
742 nextProto, ok := msg.(*nextProtoMsg)
743 if !ok {
744 c.sendAlert(alertUnexpectedMessage)
745 return unexpectedMessageError(nextProto, msg)
746 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400747 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700748 c.clientProtocol = nextProto.proto
749 }
750
David Benjamind30a9902014-08-24 01:44:23 -0400751 if hs.hello.channelIDRequested {
752 msg, err := c.readHandshake()
753 if err != nil {
754 return err
755 }
756 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
757 if !ok {
758 c.sendAlert(alertUnexpectedMessage)
759 return unexpectedMessageError(encryptedExtensions, msg)
760 }
761 x := new(big.Int).SetBytes(encryptedExtensions.channelID[0:32])
762 y := new(big.Int).SetBytes(encryptedExtensions.channelID[32:64])
763 r := new(big.Int).SetBytes(encryptedExtensions.channelID[64:96])
764 s := new(big.Int).SetBytes(encryptedExtensions.channelID[96:128])
765 if !elliptic.P256().IsOnCurve(x, y) {
766 return errors.New("tls: invalid channel ID public key")
767 }
768 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
769 var resumeHash []byte
770 if isResume {
771 resumeHash = hs.sessionState.handshakeHash
772 }
773 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
774 return errors.New("tls: invalid channel ID signature")
775 }
776 c.channelID = channelID
777
778 hs.writeClientHash(encryptedExtensions.marshal())
779 }
780
Adam Langley95c29f32014-06-20 12:00:00 -0700781 msg, err := c.readHandshake()
782 if err != nil {
783 return err
784 }
785 clientFinished, ok := msg.(*finishedMsg)
786 if !ok {
787 c.sendAlert(alertUnexpectedMessage)
788 return unexpectedMessageError(clientFinished, msg)
789 }
790
791 verify := hs.finishedHash.clientSum(hs.masterSecret)
792 if len(verify) != len(clientFinished.verifyData) ||
793 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
794 c.sendAlert(alertHandshakeFailure)
795 return errors.New("tls: client's Finished message is incorrect")
796 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700797 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langley95c29f32014-06-20 12:00:00 -0700798
David Benjamin83c0bc92014-08-04 01:23:53 -0400799 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700800 return nil
801}
802
803func (hs *serverHandshakeState) sendSessionTicket() error {
Adam Langley95c29f32014-06-20 12:00:00 -0700804 c := hs.c
Adam Langley95c29f32014-06-20 12:00:00 -0700805 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -0400806 vers: c.vers,
807 cipherSuite: hs.suite.id,
808 masterSecret: hs.masterSecret,
809 certificates: hs.certsFromClient,
810 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -0700811 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500812
813 if !hs.hello.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
814 if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
815 c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
816 }
817 return nil
818 }
819
820 m := new(newSessionTicketMsg)
821
822 var err error
Adam Langley95c29f32014-06-20 12:00:00 -0700823 m.ticket, err = c.encryptTicket(&state)
824 if err != nil {
825 return err
826 }
Adam Langley95c29f32014-06-20 12:00:00 -0700827
David Benjamin83c0bc92014-08-04 01:23:53 -0400828 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700829 c.writeRecord(recordTypeHandshake, m.marshal())
830
831 return nil
832}
833
834func (hs *serverHandshakeState) sendFinished() error {
835 c := hs.c
836
David Benjamin86271ee2014-07-21 16:14:03 -0400837 finished := new(finishedMsg)
838 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
Adam Langley2ae77d22014-10-28 17:29:33 -0700839 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -0500840 hs.finishedBytes = finished.marshal()
841 hs.writeServerHash(hs.finishedBytes)
842 postCCSBytes := hs.finishedBytes
David Benjamin86271ee2014-07-21 16:14:03 -0400843
844 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
845 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
846 postCCSBytes = postCCSBytes[5:]
847 }
David Benjamina4e6d482015-03-02 19:10:53 -0500848 c.dtlsFlushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -0400849
David Benjamina0e52232014-07-19 17:39:58 -0400850 if !c.config.Bugs.SkipChangeCipherSpec {
851 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
852 }
Adam Langley95c29f32014-06-20 12:00:00 -0700853
David Benjamin4189bd92015-01-25 23:52:39 -0500854 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
855 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
856 }
857
David Benjaminb80168e2015-02-08 18:30:14 -0500858 if !c.config.Bugs.SkipFinished {
859 c.writeRecord(recordTypeHandshake, postCCSBytes)
David Benjamina4e6d482015-03-02 19:10:53 -0500860 c.dtlsFlushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -0500861 }
Adam Langley95c29f32014-06-20 12:00:00 -0700862
863 c.cipherSuite = hs.suite.id
864
865 return nil
866}
867
868// processCertsFromClient takes a chain of client certificates either from a
869// Certificates message or from a sessionState and verifies them. It returns
870// the public key of the leaf certificate.
871func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
872 c := hs.c
873
874 hs.certsFromClient = certificates
875 certs := make([]*x509.Certificate, len(certificates))
876 var err error
877 for i, asn1Data := range certificates {
878 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
879 c.sendAlert(alertBadCertificate)
880 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
881 }
882 }
883
884 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
885 opts := x509.VerifyOptions{
886 Roots: c.config.ClientCAs,
887 CurrentTime: c.config.time(),
888 Intermediates: x509.NewCertPool(),
889 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
890 }
891
892 for _, cert := range certs[1:] {
893 opts.Intermediates.AddCert(cert)
894 }
895
896 chains, err := certs[0].Verify(opts)
897 if err != nil {
898 c.sendAlert(alertBadCertificate)
899 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
900 }
901
902 ok := false
903 for _, ku := range certs[0].ExtKeyUsage {
904 if ku == x509.ExtKeyUsageClientAuth {
905 ok = true
906 break
907 }
908 }
909 if !ok {
910 c.sendAlert(alertHandshakeFailure)
911 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
912 }
913
914 c.verifiedChains = chains
915 }
916
917 if len(certs) > 0 {
918 var pub crypto.PublicKey
919 switch key := certs[0].PublicKey.(type) {
920 case *ecdsa.PublicKey, *rsa.PublicKey:
921 pub = key
922 default:
923 c.sendAlert(alertUnsupportedCertificate)
924 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
925 }
926 c.peerCertificates = certs
927 return pub, nil
928 }
929
930 return nil, nil
931}
932
David Benjamin83c0bc92014-08-04 01:23:53 -0400933func (hs *serverHandshakeState) writeServerHash(msg []byte) {
934 // writeServerHash is called before writeRecord.
935 hs.writeHash(msg, hs.c.sendHandshakeSeq)
936}
937
938func (hs *serverHandshakeState) writeClientHash(msg []byte) {
939 // writeClientHash is called after readHandshake.
940 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
941}
942
943func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
944 if hs.c.isDTLS {
945 // This is somewhat hacky. DTLS hashes a slightly different format.
946 // First, the TLS header.
947 hs.finishedHash.Write(msg[:4])
948 // Then the sequence number and reassembled fragment offset (always 0).
949 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
950 // Then the reassembled fragment (always equal to the message length).
951 hs.finishedHash.Write(msg[1:4])
952 // And then the message body.
953 hs.finishedHash.Write(msg[4:])
954 } else {
955 hs.finishedHash.Write(msg)
956 }
957}
958
Adam Langley95c29f32014-06-20 12:00:00 -0700959// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
960// is acceptable to use.
961func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
962 for _, supported := range supportedCipherSuites {
963 if id == supported {
964 var candidate *cipherSuite
965
966 for _, s := range cipherSuites {
967 if s.id == id {
968 candidate = s
969 break
970 }
971 }
972 if candidate == nil {
973 continue
974 }
975 // Don't select a ciphersuite which we can't
976 // support for this client.
977 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
978 continue
979 }
980 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
981 continue
982 }
David Benjamin39ebf532014-08-31 02:23:49 -0400983 if !c.config.Bugs.SkipCipherVersionCheck && version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700984 continue
985 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400986 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
987 continue
988 }
Adam Langley95c29f32014-06-20 12:00:00 -0700989 return candidate
990 }
991 }
992
993 return nil
994}