blob: 5db0487903f8825e35095e5cd7674bc670a844c5 [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 }
David Benjamin72dc7832015-03-16 17:49:43 -0400196 if config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
197 hs.clientHello.signatureAndHashes = config.signatureAndHashesForServer()
198 }
David Benjamin6ae7f072015-01-26 10:22:13 -0500199
David Benjamin8bc38f52014-08-16 12:07:27 -0400200 c.vers, ok = config.mutualVersion(hs.clientHello.vers)
201 if !ok {
202 c.sendAlert(alertProtocolVersion)
203 return false, fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
204 }
Adam Langley95c29f32014-06-20 12:00:00 -0700205 c.haveVers = true
206
207 hs.hello = new(serverHelloMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400208 hs.hello.isDTLS = c.isDTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700209
210 supportedCurve := false
211 preferredCurves := config.curvePreferences()
212Curves:
213 for _, curve := range hs.clientHello.supportedCurves {
214 for _, supported := range preferredCurves {
215 if supported == curve {
216 supportedCurve = true
217 break Curves
218 }
219 }
220 }
221
222 supportedPointFormat := false
223 for _, pointFormat := range hs.clientHello.supportedPoints {
224 if pointFormat == pointFormatUncompressed {
225 supportedPointFormat = true
226 break
227 }
228 }
229 hs.ellipticOk = supportedCurve && supportedPointFormat
230
231 foundCompression := false
232 // We only support null compression, so check that the client offered it.
233 for _, compression := range hs.clientHello.compressionMethods {
234 if compression == compressionNone {
235 foundCompression = true
236 break
237 }
238 }
239
240 if !foundCompression {
241 c.sendAlert(alertHandshakeFailure)
242 return false, errors.New("tls: client does not support uncompressed connections")
243 }
244
245 hs.hello.vers = c.vers
246 hs.hello.random = make([]byte, 32)
247 _, err = io.ReadFull(config.rand(), hs.hello.random)
248 if err != nil {
249 c.sendAlert(alertInternalError)
250 return false, err
251 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700252
Adam Langleycf2d4f42014-10-28 19:06:14 -0700253 if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) {
Adam Langley2ae77d22014-10-28 17:29:33 -0700254 c.sendAlert(alertHandshakeFailure)
Adam Langleycf2d4f42014-10-28 19:06:14 -0700255 return false, errors.New("tls: renegotiation mismatch")
Adam Langley2ae77d22014-10-28 17:29:33 -0700256 }
Adam Langleycf2d4f42014-10-28 19:06:14 -0700257
258 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
259 hs.hello.secureRenegotiation = append(hs.hello.secureRenegotiation, c.clientVerify...)
260 hs.hello.secureRenegotiation = append(hs.hello.secureRenegotiation, c.serverVerify...)
261 if c.config.Bugs.BadRenegotiationInfo {
262 hs.hello.secureRenegotiation[0] ^= 0x80
263 }
264 } else {
265 hs.hello.secureRenegotiation = hs.clientHello.secureRenegotiation
266 }
267
Adam Langley95c29f32014-06-20 12:00:00 -0700268 hs.hello.compressionMethod = compressionNone
David Benjamin35a7a442014-07-05 00:23:20 -0400269 hs.hello.duplicateExtension = c.config.Bugs.DuplicateExtension
Adam Langley95c29f32014-06-20 12:00:00 -0700270 if len(hs.clientHello.serverName) > 0 {
271 c.serverName = hs.clientHello.serverName
272 }
David Benjaminfa055a22014-09-15 16:51:51 -0400273
274 if len(hs.clientHello.alpnProtocols) > 0 {
275 if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
276 hs.hello.alpnProtocol = selectedProto
277 c.clientProtocol = selectedProto
David Benjaminfc7b0862014-09-06 13:21:53 -0400278 c.usedALPN = true
David Benjaminfa055a22014-09-15 16:51:51 -0400279 }
280 } else {
281 // Although sending an empty NPN extension is reasonable, Firefox has
282 // had a bug around this. Best to send nothing at all if
283 // config.NextProtos is empty. See
284 // https://code.google.com/p/go/issues/detail?id=5445.
285 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
286 hs.hello.nextProtoNeg = true
287 hs.hello.nextProtos = config.NextProtos
288 }
Adam Langley95c29f32014-06-20 12:00:00 -0700289 }
Adam Langley75712922014-10-10 16:23:43 -0700290 hs.hello.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !c.config.Bugs.NoExtendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700291
292 if len(config.Certificates) == 0 {
293 c.sendAlert(alertInternalError)
294 return false, errors.New("tls: no certificates configured")
295 }
296 hs.cert = &config.Certificates[0]
297 if len(hs.clientHello.serverName) > 0 {
298 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
299 }
David Benjamine78bfde2014-09-06 12:45:15 -0400300 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
301 return false, errors.New("tls: unexpected server name")
302 }
Adam Langley95c29f32014-06-20 12:00:00 -0700303
David Benjamind30a9902014-08-24 01:44:23 -0400304 if hs.clientHello.channelIDSupported && config.RequestChannelID {
305 hs.hello.channelIDRequested = true
306 }
307
David Benjaminca6c8262014-11-15 19:06:08 -0500308 if hs.clientHello.srtpProtectionProfiles != nil {
309 SRTPLoop:
310 for _, p1 := range c.config.SRTPProtectionProfiles {
311 for _, p2 := range hs.clientHello.srtpProtectionProfiles {
312 if p1 == p2 {
313 hs.hello.srtpProtectionProfile = p1
314 c.srtpProtectionProfile = p1
315 break SRTPLoop
316 }
317 }
318 }
319 }
320
321 if c.config.Bugs.SendSRTPProtectionProfile != 0 {
322 hs.hello.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
323 }
324
Adam Langley95c29f32014-06-20 12:00:00 -0700325 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
326
327 if hs.checkForResumption() {
328 return true, nil
329 }
330
Adam Langleyac61fa32014-06-23 12:03:11 -0700331 var scsvFound bool
332
333 for _, cipherSuite := range hs.clientHello.cipherSuites {
334 if cipherSuite == fallbackSCSV {
335 scsvFound = true
336 break
337 }
338 }
339
340 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
341 return false, errors.New("tls: no fallback SCSV found when expected")
342 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
343 return false, errors.New("tls: fallback SCSV found when not expected")
344 }
345
David Benjamin67d1fb52015-03-16 15:16:23 -0400346 if config.Bugs.IgnorePeerCipherPreferences {
347 hs.clientHello.cipherSuites = c.config.cipherSuites()
348 }
Adam Langley95c29f32014-06-20 12:00:00 -0700349 var preferenceList, supportedList []uint16
350 if c.config.PreferServerCipherSuites {
351 preferenceList = c.config.cipherSuites()
352 supportedList = hs.clientHello.cipherSuites
353 } else {
354 preferenceList = hs.clientHello.cipherSuites
355 supportedList = c.config.cipherSuites()
356 }
357
358 for _, id := range preferenceList {
359 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
360 break
361 }
362 }
363
364 if hs.suite == nil {
365 c.sendAlert(alertHandshakeFailure)
366 return false, errors.New("tls: no cipher suite supported by both client and server")
367 }
368
369 return false, nil
370}
371
372// checkForResumption returns true if we should perform resumption on this connection.
373func (hs *serverHandshakeState) checkForResumption() bool {
374 c := hs.c
375
David Benjamincdea40c2015-03-19 14:09:43 -0400376 if c.config.Bugs.NeverResumeOnRenego && c.cipherSuite != 0 {
377 return false
378 }
379
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500380 if len(hs.clientHello.sessionTicket) > 0 {
381 if c.config.SessionTicketsDisabled {
382 return false
383 }
David Benjaminb0c8db72014-09-24 15:19:56 -0400384
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500385 var ok bool
386 if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
387 return false
388 }
389 } else {
390 if c.config.ServerSessionCache == nil {
391 return false
392 }
393
394 var ok bool
395 sessionId := string(hs.clientHello.sessionId)
396 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
397 return false
398 }
Adam Langley95c29f32014-06-20 12:00:00 -0700399 }
400
David Benjamine18d8212014-11-10 02:37:15 -0500401 // Never resume a session for a different SSL version.
402 if !c.config.Bugs.AllowSessionVersionMismatch && c.vers != hs.sessionState.vers {
403 return false
Adam Langley95c29f32014-06-20 12:00:00 -0700404 }
405
406 cipherSuiteOk := false
407 // Check that the client is still offering the ciphersuite in the session.
408 for _, id := range hs.clientHello.cipherSuites {
409 if id == hs.sessionState.cipherSuite {
410 cipherSuiteOk = true
411 break
412 }
413 }
414 if !cipherSuiteOk {
415 return false
416 }
417
418 // Check that we also support the ciphersuite from the session.
419 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk)
420 if hs.suite == nil {
421 return false
422 }
423
424 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
425 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
426 if needClientCerts && !sessionHasClientCerts {
427 return false
428 }
429 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
430 return false
431 }
432
433 return true
434}
435
436func (hs *serverHandshakeState) doResumeHandshake() error {
437 c := hs.c
438
439 hs.hello.cipherSuite = hs.suite.id
440 // We echo the client's session ID in the ServerHello to let it know
441 // that we're doing a resumption.
442 hs.hello.sessionId = hs.clientHello.sessionId
David Benjaminbed9aae2014-08-07 19:13:38 -0400443 hs.hello.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -0700444
445 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -0400446 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -0400447 hs.writeClientHash(hs.clientHello.marshal())
448 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700449
450 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
451
452 if len(hs.sessionState.certificates) > 0 {
453 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
454 return err
455 }
456 }
457
458 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -0700459 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700460
461 return nil
462}
463
464func (hs *serverHandshakeState) doFullHandshake() error {
465 config := hs.c.config
466 c := hs.c
467
David Benjamin48cae082014-10-27 01:06:24 -0400468 isPSK := hs.suite.flags&suitePSK != 0
469 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700470 hs.hello.ocspStapling = true
471 }
472
David Benjamin61f95272014-11-25 01:55:35 -0500473 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
474 hs.hello.sctList = hs.cert.SignedCertificateTimestampList
475 }
476
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500477 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
Adam Langley95c29f32014-06-20 12:00:00 -0700478 hs.hello.cipherSuite = hs.suite.id
David Benjamin6095de82014-12-27 01:50:38 -0500479 if config.Bugs.SendCipherSuite != 0 {
480 hs.hello.cipherSuite = config.Bugs.SendCipherSuite
481 }
Adam Langley75712922014-10-10 16:23:43 -0700482 c.extendedMasterSecret = hs.hello.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700483
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500484 // Generate a session ID if we're to save the session.
485 if !hs.hello.ticketSupported && config.ServerSessionCache != nil {
486 hs.hello.sessionId = make([]byte, 32)
487 if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
488 c.sendAlert(alertInternalError)
489 return errors.New("tls: short read from Rand: " + err.Error())
490 }
491 }
492
Adam Langley95c29f32014-06-20 12:00:00 -0700493 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400494 hs.writeClientHash(hs.clientHello.marshal())
495 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700496
497 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
498
David Benjamin48cae082014-10-27 01:06:24 -0400499 if !isPSK {
500 certMsg := new(certificateMsg)
501 certMsg.certificates = hs.cert.Certificate
502 if !config.Bugs.UnauthenticatedECDH {
David Benjaminbcb2d912015-02-24 23:45:43 -0500503 certMsgBytes := certMsg.marshal()
504 if config.Bugs.WrongCertificateMessageType {
505 certMsgBytes[0] += 42
506 }
507 hs.writeServerHash(certMsgBytes)
508 c.writeRecord(recordTypeHandshake, certMsgBytes)
David Benjamin48cae082014-10-27 01:06:24 -0400509 }
David Benjamin1c375dd2014-07-12 00:48:23 -0400510 }
Adam Langley95c29f32014-06-20 12:00:00 -0700511
512 if hs.hello.ocspStapling {
513 certStatus := new(certificateStatusMsg)
514 certStatus.statusType = statusTypeOCSP
515 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -0400516 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700517 c.writeRecord(recordTypeHandshake, certStatus.marshal())
518 }
519
520 keyAgreement := hs.suite.ka(c.vers)
521 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
522 if err != nil {
523 c.sendAlert(alertHandshakeFailure)
524 return err
525 }
David Benjamin9c651c92014-07-12 13:27:45 -0400526 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -0400527 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700528 c.writeRecord(recordTypeHandshake, skx.marshal())
529 }
530
531 if config.ClientAuth >= RequestClientCert {
532 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -0400533 certReq := &certificateRequestMsg{
534 certificateTypes: config.ClientCertificateTypes,
535 }
536 if certReq.certificateTypes == nil {
537 certReq.certificateTypes = []byte{
538 byte(CertTypeRSASign),
539 byte(CertTypeECDSASign),
540 }
Adam Langley95c29f32014-06-20 12:00:00 -0700541 }
542 if c.vers >= VersionTLS12 {
543 certReq.hasSignatureAndHash = true
David Benjamin000800a2014-11-14 01:43:59 -0500544 if !config.Bugs.NoSignatureAndHashes {
545 certReq.signatureAndHashes = config.signatureAndHashesForServer()
546 }
Adam Langley95c29f32014-06-20 12:00:00 -0700547 }
548
549 // An empty list of certificateAuthorities signals to
550 // the client that it may send any certificate in response
551 // to our request. When we know the CAs we trust, then
552 // we can send them down, so that the client can choose
553 // an appropriate certificate to give to us.
554 if config.ClientCAs != nil {
555 certReq.certificateAuthorities = config.ClientCAs.Subjects()
556 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400557 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700558 c.writeRecord(recordTypeHandshake, certReq.marshal())
559 }
560
561 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400562 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700563 c.writeRecord(recordTypeHandshake, helloDone.marshal())
David Benjamina4e6d482015-03-02 19:10:53 -0500564 c.dtlsFlushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700565
566 var pub crypto.PublicKey // public key for client auth, if any
567
David Benjamin83f90402015-01-27 01:09:43 -0500568 if err := c.simulatePacketLoss(nil); err != nil {
569 return err
570 }
Adam Langley95c29f32014-06-20 12:00:00 -0700571 msg, err := c.readHandshake()
572 if err != nil {
573 return err
574 }
575
576 var ok bool
577 // If we requested a client certificate, then the client must send a
578 // certificate message, even if it's empty.
579 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -0400580 var certMsg *certificateMsg
Adam Langley95c29f32014-06-20 12:00:00 -0700581 if certMsg, ok = msg.(*certificateMsg); !ok {
582 c.sendAlert(alertUnexpectedMessage)
583 return unexpectedMessageError(certMsg, msg)
584 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400585 hs.writeClientHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700586
587 if len(certMsg.certificates) == 0 {
588 // The client didn't actually send a certificate
589 switch config.ClientAuth {
590 case RequireAnyClientCert, RequireAndVerifyClientCert:
591 c.sendAlert(alertBadCertificate)
592 return errors.New("tls: client didn't provide a certificate")
593 }
594 }
595
596 pub, err = hs.processCertsFromClient(certMsg.certificates)
597 if err != nil {
598 return err
599 }
600
601 msg, err = c.readHandshake()
602 if err != nil {
603 return err
604 }
605 }
606
607 // Get client key exchange
608 ckx, ok := msg.(*clientKeyExchangeMsg)
609 if !ok {
610 c.sendAlert(alertUnexpectedMessage)
611 return unexpectedMessageError(ckx, msg)
612 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400613 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700614
David Benjamine098ec22014-08-27 23:13:20 -0400615 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
616 if err != nil {
617 c.sendAlert(alertHandshakeFailure)
618 return err
619 }
Adam Langley75712922014-10-10 16:23:43 -0700620 if c.extendedMasterSecret {
621 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
622 } else {
623 if c.config.Bugs.RequireExtendedMasterSecret {
624 return errors.New("tls: extended master secret required but not supported by peer")
625 }
626 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
627 }
David Benjamine098ec22014-08-27 23:13:20 -0400628
Adam Langley95c29f32014-06-20 12:00:00 -0700629 // If we received a client cert in response to our certificate request message,
630 // the client will send us a certificateVerifyMsg immediately after the
631 // clientKeyExchangeMsg. This message is a digest of all preceding
632 // handshake-layer messages that is signed using the private key corresponding
633 // to the client's certificate. This allows us to verify that the client is in
634 // possession of the private key of the certificate.
635 if len(c.peerCertificates) > 0 {
636 msg, err = c.readHandshake()
637 if err != nil {
638 return err
639 }
640 certVerify, ok := msg.(*certificateVerifyMsg)
641 if !ok {
642 c.sendAlert(alertUnexpectedMessage)
643 return unexpectedMessageError(certVerify, msg)
644 }
645
David Benjaminde620d92014-07-18 15:03:41 -0400646 // Determine the signature type.
647 var signatureAndHash signatureAndHash
648 if certVerify.hasSignatureAndHash {
649 signatureAndHash = certVerify.signatureAndHash
David Benjamin000800a2014-11-14 01:43:59 -0500650 if !isSupportedSignatureAndHash(signatureAndHash, config.signatureAndHashesForServer()) {
651 return errors.New("tls: unsupported hash function for client certificate")
652 }
David Benjaminde620d92014-07-18 15:03:41 -0400653 } else {
654 // Before TLS 1.2 the signature algorithm was implicit
655 // from the key type, and only one hash per signature
656 // algorithm was possible. Leave the hash as zero.
657 switch pub.(type) {
658 case *ecdsa.PublicKey:
659 signatureAndHash.signature = signatureECDSA
660 case *rsa.PublicKey:
661 signatureAndHash.signature = signatureRSA
662 }
663 }
664
Adam Langley95c29f32014-06-20 12:00:00 -0700665 switch key := pub.(type) {
666 case *ecdsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400667 if signatureAndHash.signature != signatureECDSA {
668 err = errors.New("tls: bad signature type for client's ECDSA certificate")
669 break
670 }
Adam Langley95c29f32014-06-20 12:00:00 -0700671 ecdsaSig := new(ecdsaSignature)
672 if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {
673 break
674 }
675 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
676 err = errors.New("ECDSA signature contained zero or negative values")
677 break
678 }
David Benjaminde620d92014-07-18 15:03:41 -0400679 var digest []byte
David Benjamine098ec22014-08-27 23:13:20 -0400680 digest, _, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400681 if err != nil {
682 break
683 }
Adam Langley95c29f32014-06-20 12:00:00 -0700684 if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {
685 err = errors.New("ECDSA verification failure")
686 break
687 }
688 case *rsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400689 if signatureAndHash.signature != signatureRSA {
690 err = errors.New("tls: bad signature type for client's RSA certificate")
691 break
692 }
693 var digest []byte
694 var hashFunc crypto.Hash
David Benjamine098ec22014-08-27 23:13:20 -0400695 digest, hashFunc, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400696 if err != nil {
697 break
698 }
Adam Langley95c29f32014-06-20 12:00:00 -0700699 err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)
700 }
701 if err != nil {
702 c.sendAlert(alertBadCertificate)
703 return errors.New("could not validate signature of connection nonces: " + err.Error())
704 }
705
David Benjamin83c0bc92014-08-04 01:23:53 -0400706 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700707 }
708
David Benjamine098ec22014-08-27 23:13:20 -0400709 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -0700710
711 return nil
712}
713
714func (hs *serverHandshakeState) establishKeys() error {
715 c := hs.c
716
717 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
718 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
719
720 var clientCipher, serverCipher interface{}
721 var clientHash, serverHash macFunction
722
723 if hs.suite.aead == nil {
724 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
725 clientHash = hs.suite.mac(c.vers, clientMAC)
726 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
727 serverHash = hs.suite.mac(c.vers, serverMAC)
728 } else {
729 clientCipher = hs.suite.aead(clientKey, clientIV)
730 serverCipher = hs.suite.aead(serverKey, serverIV)
731 }
732
733 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
734 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
735
736 return nil
737}
738
David Benjamind30a9902014-08-24 01:44:23 -0400739func (hs *serverHandshakeState) readFinished(isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700740 c := hs.c
741
742 c.readRecord(recordTypeChangeCipherSpec)
743 if err := c.in.error(); err != nil {
744 return err
745 }
746
747 if hs.hello.nextProtoNeg {
748 msg, err := c.readHandshake()
749 if err != nil {
750 return err
751 }
752 nextProto, ok := msg.(*nextProtoMsg)
753 if !ok {
754 c.sendAlert(alertUnexpectedMessage)
755 return unexpectedMessageError(nextProto, msg)
756 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400757 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700758 c.clientProtocol = nextProto.proto
759 }
760
David Benjamind30a9902014-08-24 01:44:23 -0400761 if hs.hello.channelIDRequested {
762 msg, err := c.readHandshake()
763 if err != nil {
764 return err
765 }
766 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
767 if !ok {
768 c.sendAlert(alertUnexpectedMessage)
769 return unexpectedMessageError(encryptedExtensions, msg)
770 }
771 x := new(big.Int).SetBytes(encryptedExtensions.channelID[0:32])
772 y := new(big.Int).SetBytes(encryptedExtensions.channelID[32:64])
773 r := new(big.Int).SetBytes(encryptedExtensions.channelID[64:96])
774 s := new(big.Int).SetBytes(encryptedExtensions.channelID[96:128])
775 if !elliptic.P256().IsOnCurve(x, y) {
776 return errors.New("tls: invalid channel ID public key")
777 }
778 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
779 var resumeHash []byte
780 if isResume {
781 resumeHash = hs.sessionState.handshakeHash
782 }
783 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
784 return errors.New("tls: invalid channel ID signature")
785 }
786 c.channelID = channelID
787
788 hs.writeClientHash(encryptedExtensions.marshal())
789 }
790
Adam Langley95c29f32014-06-20 12:00:00 -0700791 msg, err := c.readHandshake()
792 if err != nil {
793 return err
794 }
795 clientFinished, ok := msg.(*finishedMsg)
796 if !ok {
797 c.sendAlert(alertUnexpectedMessage)
798 return unexpectedMessageError(clientFinished, msg)
799 }
800
801 verify := hs.finishedHash.clientSum(hs.masterSecret)
802 if len(verify) != len(clientFinished.verifyData) ||
803 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
804 c.sendAlert(alertHandshakeFailure)
805 return errors.New("tls: client's Finished message is incorrect")
806 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700807 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langley95c29f32014-06-20 12:00:00 -0700808
David Benjamin83c0bc92014-08-04 01:23:53 -0400809 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700810 return nil
811}
812
813func (hs *serverHandshakeState) sendSessionTicket() error {
Adam Langley95c29f32014-06-20 12:00:00 -0700814 c := hs.c
Adam Langley95c29f32014-06-20 12:00:00 -0700815 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -0400816 vers: c.vers,
817 cipherSuite: hs.suite.id,
818 masterSecret: hs.masterSecret,
819 certificates: hs.certsFromClient,
820 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -0700821 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500822
823 if !hs.hello.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
824 if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
825 c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
826 }
827 return nil
828 }
829
830 m := new(newSessionTicketMsg)
831
832 var err error
Adam Langley95c29f32014-06-20 12:00:00 -0700833 m.ticket, err = c.encryptTicket(&state)
834 if err != nil {
835 return err
836 }
Adam Langley95c29f32014-06-20 12:00:00 -0700837
David Benjamin83c0bc92014-08-04 01:23:53 -0400838 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700839 c.writeRecord(recordTypeHandshake, m.marshal())
840
841 return nil
842}
843
844func (hs *serverHandshakeState) sendFinished() error {
845 c := hs.c
846
David Benjamin86271ee2014-07-21 16:14:03 -0400847 finished := new(finishedMsg)
848 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
David Benjamin513f0ea2015-04-02 19:33:31 -0400849 if c.config.Bugs.BadFinished {
850 finished.verifyData[0]++
851 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700852 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -0500853 hs.finishedBytes = finished.marshal()
854 hs.writeServerHash(hs.finishedBytes)
855 postCCSBytes := hs.finishedBytes
David Benjamin86271ee2014-07-21 16:14:03 -0400856
857 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
858 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
859 postCCSBytes = postCCSBytes[5:]
860 }
David Benjamina4e6d482015-03-02 19:10:53 -0500861 c.dtlsFlushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -0400862
David Benjamina0e52232014-07-19 17:39:58 -0400863 if !c.config.Bugs.SkipChangeCipherSpec {
864 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
865 }
Adam Langley95c29f32014-06-20 12:00:00 -0700866
David Benjamin4189bd92015-01-25 23:52:39 -0500867 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
868 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
869 }
David Benjamindc3da932015-03-12 15:09:02 -0400870 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
871 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
872 return errors.New("tls: simulating post-CCS alert")
873 }
David Benjamin4189bd92015-01-25 23:52:39 -0500874
David Benjaminb80168e2015-02-08 18:30:14 -0500875 if !c.config.Bugs.SkipFinished {
876 c.writeRecord(recordTypeHandshake, postCCSBytes)
David Benjamina4e6d482015-03-02 19:10:53 -0500877 c.dtlsFlushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -0500878 }
Adam Langley95c29f32014-06-20 12:00:00 -0700879
880 c.cipherSuite = hs.suite.id
881
882 return nil
883}
884
885// processCertsFromClient takes a chain of client certificates either from a
886// Certificates message or from a sessionState and verifies them. It returns
887// the public key of the leaf certificate.
888func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
889 c := hs.c
890
891 hs.certsFromClient = certificates
892 certs := make([]*x509.Certificate, len(certificates))
893 var err error
894 for i, asn1Data := range certificates {
895 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
896 c.sendAlert(alertBadCertificate)
897 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
898 }
899 }
900
901 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
902 opts := x509.VerifyOptions{
903 Roots: c.config.ClientCAs,
904 CurrentTime: c.config.time(),
905 Intermediates: x509.NewCertPool(),
906 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
907 }
908
909 for _, cert := range certs[1:] {
910 opts.Intermediates.AddCert(cert)
911 }
912
913 chains, err := certs[0].Verify(opts)
914 if err != nil {
915 c.sendAlert(alertBadCertificate)
916 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
917 }
918
919 ok := false
920 for _, ku := range certs[0].ExtKeyUsage {
921 if ku == x509.ExtKeyUsageClientAuth {
922 ok = true
923 break
924 }
925 }
926 if !ok {
927 c.sendAlert(alertHandshakeFailure)
928 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
929 }
930
931 c.verifiedChains = chains
932 }
933
934 if len(certs) > 0 {
935 var pub crypto.PublicKey
936 switch key := certs[0].PublicKey.(type) {
937 case *ecdsa.PublicKey, *rsa.PublicKey:
938 pub = key
939 default:
940 c.sendAlert(alertUnsupportedCertificate)
941 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
942 }
943 c.peerCertificates = certs
944 return pub, nil
945 }
946
947 return nil, nil
948}
949
David Benjamin83c0bc92014-08-04 01:23:53 -0400950func (hs *serverHandshakeState) writeServerHash(msg []byte) {
951 // writeServerHash is called before writeRecord.
952 hs.writeHash(msg, hs.c.sendHandshakeSeq)
953}
954
955func (hs *serverHandshakeState) writeClientHash(msg []byte) {
956 // writeClientHash is called after readHandshake.
957 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
958}
959
960func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
961 if hs.c.isDTLS {
962 // This is somewhat hacky. DTLS hashes a slightly different format.
963 // First, the TLS header.
964 hs.finishedHash.Write(msg[:4])
965 // Then the sequence number and reassembled fragment offset (always 0).
966 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
967 // Then the reassembled fragment (always equal to the message length).
968 hs.finishedHash.Write(msg[1:4])
969 // And then the message body.
970 hs.finishedHash.Write(msg[4:])
971 } else {
972 hs.finishedHash.Write(msg)
973 }
974}
975
Adam Langley95c29f32014-06-20 12:00:00 -0700976// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
977// is acceptable to use.
978func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
979 for _, supported := range supportedCipherSuites {
980 if id == supported {
981 var candidate *cipherSuite
982
983 for _, s := range cipherSuites {
984 if s.id == id {
985 candidate = s
986 break
987 }
988 }
989 if candidate == nil {
990 continue
991 }
992 // Don't select a ciphersuite which we can't
993 // support for this client.
994 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
995 continue
996 }
997 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
998 continue
999 }
David Benjamin39ebf532014-08-31 02:23:49 -04001000 if !c.config.Bugs.SkipCipherVersionCheck && version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
Adam Langley95c29f32014-06-20 12:00:00 -07001001 continue
1002 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001003 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
1004 continue
1005 }
Adam Langley95c29f32014-06-20 12:00:00 -07001006 return candidate
1007 }
1008 }
1009
1010 return nil
1011}