blob: cf9d1ca23311bf47c065664d3684fc2166ee4059 [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 Benjamin1c633152015-04-02 20:19:11 -0400100 if c.config.Bugs.AlertBeforeFalseStartTest != 0 {
101 c.sendAlert(c.config.Bugs.AlertBeforeFalseStartTest)
102 }
David Benjamine58c4f52014-08-24 03:47:07 -0400103 if c.config.Bugs.ExpectFalseStart {
104 if err := c.readRecord(recordTypeApplicationData); err != nil {
David Benjamin1c633152015-04-02 20:19:11 -0400105 return fmt.Errorf("tls: peer did not false start: %s", err)
David Benjamine58c4f52014-08-24 03:47:07 -0400106 }
107 }
Adam Langley95c29f32014-06-20 12:00:00 -0700108 if err := hs.sendSessionTicket(); err != nil {
109 return err
110 }
111 if err := hs.sendFinished(); err != nil {
112 return err
113 }
114 }
115 c.handshakeComplete = true
116
117 return nil
118}
119
120// readClientHello reads a ClientHello message from the client and decides
121// whether we will perform session resumption.
122func (hs *serverHandshakeState) readClientHello() (isResume bool, err error) {
123 config := hs.c.config
124 c := hs.c
125
David Benjamin83f90402015-01-27 01:09:43 -0500126 if err := c.simulatePacketLoss(nil); err != nil {
127 return false, err
128 }
Adam Langley95c29f32014-06-20 12:00:00 -0700129 msg, err := c.readHandshake()
130 if err != nil {
131 return false, err
132 }
133 var ok bool
134 hs.clientHello, ok = msg.(*clientHelloMsg)
135 if !ok {
136 c.sendAlert(alertUnexpectedMessage)
137 return false, unexpectedMessageError(hs.clientHello, msg)
138 }
Feng Lu41aa3252014-11-21 22:47:56 -0800139 if config.Bugs.RequireFastradioPadding && len(hs.clientHello.raw) < 1000 {
140 return false, errors.New("tls: ClientHello record size should be larger than 1000 bytes when padding enabled.")
141 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400142
143 if c.isDTLS && !config.Bugs.SkipHelloVerifyRequest {
David Benjamin8bc38f52014-08-16 12:07:27 -0400144 // Per RFC 6347, the version field in HelloVerifyRequest SHOULD
145 // be always DTLS 1.0
David Benjamin83c0bc92014-08-04 01:23:53 -0400146 helloVerifyRequest := &helloVerifyRequestMsg{
David Benjamin8bc38f52014-08-16 12:07:27 -0400147 vers: VersionTLS10,
David Benjamin83c0bc92014-08-04 01:23:53 -0400148 cookie: make([]byte, 32),
149 }
150 if _, err := io.ReadFull(c.config.rand(), helloVerifyRequest.cookie); err != nil {
151 c.sendAlert(alertInternalError)
152 return false, errors.New("dtls: short read from Rand: " + err.Error())
153 }
154 c.writeRecord(recordTypeHandshake, helloVerifyRequest.marshal())
David Benjamina4e6d482015-03-02 19:10:53 -0500155 c.dtlsFlushHandshake()
David Benjamin83c0bc92014-08-04 01:23:53 -0400156
David Benjamin83f90402015-01-27 01:09:43 -0500157 if err := c.simulatePacketLoss(nil); err != nil {
158 return false, err
159 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400160 msg, err := c.readHandshake()
161 if err != nil {
162 return false, err
163 }
164 newClientHello, ok := msg.(*clientHelloMsg)
165 if !ok {
166 c.sendAlert(alertUnexpectedMessage)
167 return false, unexpectedMessageError(hs.clientHello, msg)
168 }
169 if !bytes.Equal(newClientHello.cookie, helloVerifyRequest.cookie) {
170 return false, errors.New("dtls: invalid cookie")
171 }
David Benjaminf2fedef2014-08-16 01:37:34 -0400172
173 // Apart from the cookie, the two ClientHellos must
174 // match. Note that clientHello.equal compares the
175 // serialization, so we make a copy.
176 oldClientHelloCopy := *hs.clientHello
177 oldClientHelloCopy.raw = nil
178 oldClientHelloCopy.cookie = nil
179 newClientHelloCopy := *newClientHello
180 newClientHelloCopy.raw = nil
181 newClientHelloCopy.cookie = nil
182 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400183 return false, errors.New("dtls: retransmitted ClientHello does not match")
184 }
185 hs.clientHello = newClientHello
186 }
187
David Benjaminc44b1df2014-11-23 12:11:01 -0500188 if config.Bugs.RequireSameRenegoClientVersion && c.clientVersion != 0 {
189 if c.clientVersion != hs.clientHello.vers {
190 return false, fmt.Errorf("tls: client offered different version on renego")
191 }
192 }
193 c.clientVersion = hs.clientHello.vers
194
David Benjamin6ae7f072015-01-26 10:22:13 -0500195 // Reject < 1.2 ClientHellos with signature_algorithms.
196 if c.clientVersion < VersionTLS12 && len(hs.clientHello.signatureAndHashes) > 0 {
197 return false, fmt.Errorf("tls: client included signature_algorithms before TLS 1.2")
198 }
David Benjamin72dc7832015-03-16 17:49:43 -0400199 if config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
200 hs.clientHello.signatureAndHashes = config.signatureAndHashesForServer()
201 }
David Benjamin6ae7f072015-01-26 10:22:13 -0500202
David Benjamin8bc38f52014-08-16 12:07:27 -0400203 c.vers, ok = config.mutualVersion(hs.clientHello.vers)
204 if !ok {
205 c.sendAlert(alertProtocolVersion)
206 return false, fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
207 }
Adam Langley95c29f32014-06-20 12:00:00 -0700208 c.haveVers = true
209
210 hs.hello = new(serverHelloMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400211 hs.hello.isDTLS = c.isDTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700212
213 supportedCurve := false
214 preferredCurves := config.curvePreferences()
215Curves:
216 for _, curve := range hs.clientHello.supportedCurves {
217 for _, supported := range preferredCurves {
218 if supported == curve {
219 supportedCurve = true
220 break Curves
221 }
222 }
223 }
224
225 supportedPointFormat := false
226 for _, pointFormat := range hs.clientHello.supportedPoints {
227 if pointFormat == pointFormatUncompressed {
228 supportedPointFormat = true
229 break
230 }
231 }
232 hs.ellipticOk = supportedCurve && supportedPointFormat
233
234 foundCompression := false
235 // We only support null compression, so check that the client offered it.
236 for _, compression := range hs.clientHello.compressionMethods {
237 if compression == compressionNone {
238 foundCompression = true
239 break
240 }
241 }
242
243 if !foundCompression {
244 c.sendAlert(alertHandshakeFailure)
245 return false, errors.New("tls: client does not support uncompressed connections")
246 }
247
248 hs.hello.vers = c.vers
249 hs.hello.random = make([]byte, 32)
250 _, err = io.ReadFull(config.rand(), hs.hello.random)
251 if err != nil {
252 c.sendAlert(alertInternalError)
253 return false, err
254 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700255
Adam Langleycf2d4f42014-10-28 19:06:14 -0700256 if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) {
Adam Langley2ae77d22014-10-28 17:29:33 -0700257 c.sendAlert(alertHandshakeFailure)
Adam Langleycf2d4f42014-10-28 19:06:14 -0700258 return false, errors.New("tls: renegotiation mismatch")
Adam Langley2ae77d22014-10-28 17:29:33 -0700259 }
Adam Langleycf2d4f42014-10-28 19:06:14 -0700260
261 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
262 hs.hello.secureRenegotiation = append(hs.hello.secureRenegotiation, c.clientVerify...)
263 hs.hello.secureRenegotiation = append(hs.hello.secureRenegotiation, c.serverVerify...)
264 if c.config.Bugs.BadRenegotiationInfo {
265 hs.hello.secureRenegotiation[0] ^= 0x80
266 }
267 } else {
268 hs.hello.secureRenegotiation = hs.clientHello.secureRenegotiation
269 }
270
Adam Langley95c29f32014-06-20 12:00:00 -0700271 hs.hello.compressionMethod = compressionNone
David Benjamin35a7a442014-07-05 00:23:20 -0400272 hs.hello.duplicateExtension = c.config.Bugs.DuplicateExtension
Adam Langley95c29f32014-06-20 12:00:00 -0700273 if len(hs.clientHello.serverName) > 0 {
274 c.serverName = hs.clientHello.serverName
275 }
David Benjaminfa055a22014-09-15 16:51:51 -0400276
277 if len(hs.clientHello.alpnProtocols) > 0 {
278 if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
279 hs.hello.alpnProtocol = selectedProto
280 c.clientProtocol = selectedProto
David Benjaminfc7b0862014-09-06 13:21:53 -0400281 c.usedALPN = true
David Benjaminfa055a22014-09-15 16:51:51 -0400282 }
283 } else {
284 // Although sending an empty NPN extension is reasonable, Firefox has
285 // had a bug around this. Best to send nothing at all if
286 // config.NextProtos is empty. See
287 // https://code.google.com/p/go/issues/detail?id=5445.
288 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
289 hs.hello.nextProtoNeg = true
290 hs.hello.nextProtos = config.NextProtos
291 }
Adam Langley95c29f32014-06-20 12:00:00 -0700292 }
Adam Langley75712922014-10-10 16:23:43 -0700293 hs.hello.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !c.config.Bugs.NoExtendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700294
295 if len(config.Certificates) == 0 {
296 c.sendAlert(alertInternalError)
297 return false, errors.New("tls: no certificates configured")
298 }
299 hs.cert = &config.Certificates[0]
300 if len(hs.clientHello.serverName) > 0 {
301 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
302 }
David Benjamine78bfde2014-09-06 12:45:15 -0400303 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
304 return false, errors.New("tls: unexpected server name")
305 }
Adam Langley95c29f32014-06-20 12:00:00 -0700306
David Benjamind30a9902014-08-24 01:44:23 -0400307 if hs.clientHello.channelIDSupported && config.RequestChannelID {
308 hs.hello.channelIDRequested = true
309 }
310
David Benjaminca6c8262014-11-15 19:06:08 -0500311 if hs.clientHello.srtpProtectionProfiles != nil {
312 SRTPLoop:
313 for _, p1 := range c.config.SRTPProtectionProfiles {
314 for _, p2 := range hs.clientHello.srtpProtectionProfiles {
315 if p1 == p2 {
316 hs.hello.srtpProtectionProfile = p1
317 c.srtpProtectionProfile = p1
318 break SRTPLoop
319 }
320 }
321 }
322 }
323
324 if c.config.Bugs.SendSRTPProtectionProfile != 0 {
325 hs.hello.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
326 }
327
Adam Langley95c29f32014-06-20 12:00:00 -0700328 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
329
330 if hs.checkForResumption() {
331 return true, nil
332 }
333
Adam Langleyac61fa32014-06-23 12:03:11 -0700334 var scsvFound bool
335
336 for _, cipherSuite := range hs.clientHello.cipherSuites {
337 if cipherSuite == fallbackSCSV {
338 scsvFound = true
339 break
340 }
341 }
342
343 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
344 return false, errors.New("tls: no fallback SCSV found when expected")
345 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
346 return false, errors.New("tls: fallback SCSV found when not expected")
347 }
348
David Benjamin67d1fb52015-03-16 15:16:23 -0400349 if config.Bugs.IgnorePeerCipherPreferences {
350 hs.clientHello.cipherSuites = c.config.cipherSuites()
351 }
Adam Langley95c29f32014-06-20 12:00:00 -0700352 var preferenceList, supportedList []uint16
353 if c.config.PreferServerCipherSuites {
354 preferenceList = c.config.cipherSuites()
355 supportedList = hs.clientHello.cipherSuites
356 } else {
357 preferenceList = hs.clientHello.cipherSuites
358 supportedList = c.config.cipherSuites()
359 }
360
361 for _, id := range preferenceList {
362 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
363 break
364 }
365 }
366
367 if hs.suite == nil {
368 c.sendAlert(alertHandshakeFailure)
369 return false, errors.New("tls: no cipher suite supported by both client and server")
370 }
371
372 return false, nil
373}
374
375// checkForResumption returns true if we should perform resumption on this connection.
376func (hs *serverHandshakeState) checkForResumption() bool {
377 c := hs.c
378
David Benjamincdea40c2015-03-19 14:09:43 -0400379 if c.config.Bugs.NeverResumeOnRenego && c.cipherSuite != 0 {
380 return false
381 }
382
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500383 if len(hs.clientHello.sessionTicket) > 0 {
384 if c.config.SessionTicketsDisabled {
385 return false
386 }
David Benjaminb0c8db72014-09-24 15:19:56 -0400387
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500388 var ok bool
389 if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
390 return false
391 }
392 } else {
393 if c.config.ServerSessionCache == nil {
394 return false
395 }
396
397 var ok bool
398 sessionId := string(hs.clientHello.sessionId)
399 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
400 return false
401 }
Adam Langley95c29f32014-06-20 12:00:00 -0700402 }
403
David Benjamine18d8212014-11-10 02:37:15 -0500404 // Never resume a session for a different SSL version.
405 if !c.config.Bugs.AllowSessionVersionMismatch && c.vers != hs.sessionState.vers {
406 return false
Adam Langley95c29f32014-06-20 12:00:00 -0700407 }
408
409 cipherSuiteOk := false
410 // Check that the client is still offering the ciphersuite in the session.
411 for _, id := range hs.clientHello.cipherSuites {
412 if id == hs.sessionState.cipherSuite {
413 cipherSuiteOk = true
414 break
415 }
416 }
417 if !cipherSuiteOk {
418 return false
419 }
420
421 // Check that we also support the ciphersuite from the session.
422 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk)
423 if hs.suite == nil {
424 return false
425 }
426
427 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
428 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
429 if needClientCerts && !sessionHasClientCerts {
430 return false
431 }
432 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
433 return false
434 }
435
436 return true
437}
438
439func (hs *serverHandshakeState) doResumeHandshake() error {
440 c := hs.c
441
442 hs.hello.cipherSuite = hs.suite.id
443 // We echo the client's session ID in the ServerHello to let it know
444 // that we're doing a resumption.
445 hs.hello.sessionId = hs.clientHello.sessionId
David Benjaminbed9aae2014-08-07 19:13:38 -0400446 hs.hello.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -0700447
448 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -0400449 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -0400450 hs.writeClientHash(hs.clientHello.marshal())
451 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700452
453 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
454
455 if len(hs.sessionState.certificates) > 0 {
456 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
457 return err
458 }
459 }
460
461 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -0700462 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700463
464 return nil
465}
466
467func (hs *serverHandshakeState) doFullHandshake() error {
468 config := hs.c.config
469 c := hs.c
470
David Benjamin48cae082014-10-27 01:06:24 -0400471 isPSK := hs.suite.flags&suitePSK != 0
472 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700473 hs.hello.ocspStapling = true
474 }
475
David Benjamin61f95272014-11-25 01:55:35 -0500476 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
477 hs.hello.sctList = hs.cert.SignedCertificateTimestampList
478 }
479
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500480 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
Adam Langley95c29f32014-06-20 12:00:00 -0700481 hs.hello.cipherSuite = hs.suite.id
David Benjamin6095de82014-12-27 01:50:38 -0500482 if config.Bugs.SendCipherSuite != 0 {
483 hs.hello.cipherSuite = config.Bugs.SendCipherSuite
484 }
Adam Langley75712922014-10-10 16:23:43 -0700485 c.extendedMasterSecret = hs.hello.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700486
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500487 // Generate a session ID if we're to save the session.
488 if !hs.hello.ticketSupported && config.ServerSessionCache != nil {
489 hs.hello.sessionId = make([]byte, 32)
490 if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
491 c.sendAlert(alertInternalError)
492 return errors.New("tls: short read from Rand: " + err.Error())
493 }
494 }
495
Adam Langley95c29f32014-06-20 12:00:00 -0700496 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400497 hs.writeClientHash(hs.clientHello.marshal())
498 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700499
500 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
501
David Benjamin48cae082014-10-27 01:06:24 -0400502 if !isPSK {
503 certMsg := new(certificateMsg)
504 certMsg.certificates = hs.cert.Certificate
505 if !config.Bugs.UnauthenticatedECDH {
David Benjaminbcb2d912015-02-24 23:45:43 -0500506 certMsgBytes := certMsg.marshal()
507 if config.Bugs.WrongCertificateMessageType {
508 certMsgBytes[0] += 42
509 }
510 hs.writeServerHash(certMsgBytes)
511 c.writeRecord(recordTypeHandshake, certMsgBytes)
David Benjamin48cae082014-10-27 01:06:24 -0400512 }
David Benjamin1c375dd2014-07-12 00:48:23 -0400513 }
Adam Langley95c29f32014-06-20 12:00:00 -0700514
515 if hs.hello.ocspStapling {
516 certStatus := new(certificateStatusMsg)
517 certStatus.statusType = statusTypeOCSP
518 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -0400519 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700520 c.writeRecord(recordTypeHandshake, certStatus.marshal())
521 }
522
523 keyAgreement := hs.suite.ka(c.vers)
524 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
525 if err != nil {
526 c.sendAlert(alertHandshakeFailure)
527 return err
528 }
David Benjamin9c651c92014-07-12 13:27:45 -0400529 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -0400530 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700531 c.writeRecord(recordTypeHandshake, skx.marshal())
532 }
533
534 if config.ClientAuth >= RequestClientCert {
535 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -0400536 certReq := &certificateRequestMsg{
537 certificateTypes: config.ClientCertificateTypes,
538 }
539 if certReq.certificateTypes == nil {
540 certReq.certificateTypes = []byte{
541 byte(CertTypeRSASign),
542 byte(CertTypeECDSASign),
543 }
Adam Langley95c29f32014-06-20 12:00:00 -0700544 }
545 if c.vers >= VersionTLS12 {
546 certReq.hasSignatureAndHash = true
David Benjamin000800a2014-11-14 01:43:59 -0500547 if !config.Bugs.NoSignatureAndHashes {
548 certReq.signatureAndHashes = config.signatureAndHashesForServer()
549 }
Adam Langley95c29f32014-06-20 12:00:00 -0700550 }
551
552 // An empty list of certificateAuthorities signals to
553 // the client that it may send any certificate in response
554 // to our request. When we know the CAs we trust, then
555 // we can send them down, so that the client can choose
556 // an appropriate certificate to give to us.
557 if config.ClientCAs != nil {
558 certReq.certificateAuthorities = config.ClientCAs.Subjects()
559 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400560 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700561 c.writeRecord(recordTypeHandshake, certReq.marshal())
562 }
563
564 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400565 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700566 c.writeRecord(recordTypeHandshake, helloDone.marshal())
David Benjamina4e6d482015-03-02 19:10:53 -0500567 c.dtlsFlushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700568
569 var pub crypto.PublicKey // public key for client auth, if any
570
David Benjamin83f90402015-01-27 01:09:43 -0500571 if err := c.simulatePacketLoss(nil); err != nil {
572 return err
573 }
Adam Langley95c29f32014-06-20 12:00:00 -0700574 msg, err := c.readHandshake()
575 if err != nil {
576 return err
577 }
578
579 var ok bool
580 // If we requested a client certificate, then the client must send a
581 // certificate message, even if it's empty.
582 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -0400583 var certMsg *certificateMsg
Adam Langley95c29f32014-06-20 12:00:00 -0700584 if certMsg, ok = msg.(*certificateMsg); !ok {
585 c.sendAlert(alertUnexpectedMessage)
586 return unexpectedMessageError(certMsg, msg)
587 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400588 hs.writeClientHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700589
590 if len(certMsg.certificates) == 0 {
591 // The client didn't actually send a certificate
592 switch config.ClientAuth {
593 case RequireAnyClientCert, RequireAndVerifyClientCert:
594 c.sendAlert(alertBadCertificate)
595 return errors.New("tls: client didn't provide a certificate")
596 }
597 }
598
599 pub, err = hs.processCertsFromClient(certMsg.certificates)
600 if err != nil {
601 return err
602 }
603
604 msg, err = c.readHandshake()
605 if err != nil {
606 return err
607 }
608 }
609
610 // Get client key exchange
611 ckx, ok := msg.(*clientKeyExchangeMsg)
612 if !ok {
613 c.sendAlert(alertUnexpectedMessage)
614 return unexpectedMessageError(ckx, msg)
615 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400616 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700617
David Benjamine098ec22014-08-27 23:13:20 -0400618 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
619 if err != nil {
620 c.sendAlert(alertHandshakeFailure)
621 return err
622 }
Adam Langley75712922014-10-10 16:23:43 -0700623 if c.extendedMasterSecret {
624 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
625 } else {
626 if c.config.Bugs.RequireExtendedMasterSecret {
627 return errors.New("tls: extended master secret required but not supported by peer")
628 }
629 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
630 }
David Benjamine098ec22014-08-27 23:13:20 -0400631
Adam Langley95c29f32014-06-20 12:00:00 -0700632 // If we received a client cert in response to our certificate request message,
633 // the client will send us a certificateVerifyMsg immediately after the
634 // clientKeyExchangeMsg. This message is a digest of all preceding
635 // handshake-layer messages that is signed using the private key corresponding
636 // to the client's certificate. This allows us to verify that the client is in
637 // possession of the private key of the certificate.
638 if len(c.peerCertificates) > 0 {
639 msg, err = c.readHandshake()
640 if err != nil {
641 return err
642 }
643 certVerify, ok := msg.(*certificateVerifyMsg)
644 if !ok {
645 c.sendAlert(alertUnexpectedMessage)
646 return unexpectedMessageError(certVerify, msg)
647 }
648
David Benjaminde620d92014-07-18 15:03:41 -0400649 // Determine the signature type.
650 var signatureAndHash signatureAndHash
651 if certVerify.hasSignatureAndHash {
652 signatureAndHash = certVerify.signatureAndHash
David Benjamin000800a2014-11-14 01:43:59 -0500653 if !isSupportedSignatureAndHash(signatureAndHash, config.signatureAndHashesForServer()) {
654 return errors.New("tls: unsupported hash function for client certificate")
655 }
David Benjaminde620d92014-07-18 15:03:41 -0400656 } else {
657 // Before TLS 1.2 the signature algorithm was implicit
658 // from the key type, and only one hash per signature
659 // algorithm was possible. Leave the hash as zero.
660 switch pub.(type) {
661 case *ecdsa.PublicKey:
662 signatureAndHash.signature = signatureECDSA
663 case *rsa.PublicKey:
664 signatureAndHash.signature = signatureRSA
665 }
666 }
667
Adam Langley95c29f32014-06-20 12:00:00 -0700668 switch key := pub.(type) {
669 case *ecdsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400670 if signatureAndHash.signature != signatureECDSA {
671 err = errors.New("tls: bad signature type for client's ECDSA certificate")
672 break
673 }
Adam Langley95c29f32014-06-20 12:00:00 -0700674 ecdsaSig := new(ecdsaSignature)
675 if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {
676 break
677 }
678 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
679 err = errors.New("ECDSA signature contained zero or negative values")
680 break
681 }
David Benjaminde620d92014-07-18 15:03:41 -0400682 var digest []byte
David Benjamine098ec22014-08-27 23:13:20 -0400683 digest, _, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400684 if err != nil {
685 break
686 }
Adam Langley95c29f32014-06-20 12:00:00 -0700687 if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {
688 err = errors.New("ECDSA verification failure")
689 break
690 }
691 case *rsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400692 if signatureAndHash.signature != signatureRSA {
693 err = errors.New("tls: bad signature type for client's RSA certificate")
694 break
695 }
696 var digest []byte
697 var hashFunc crypto.Hash
David Benjamine098ec22014-08-27 23:13:20 -0400698 digest, hashFunc, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400699 if err != nil {
700 break
701 }
Adam Langley95c29f32014-06-20 12:00:00 -0700702 err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)
703 }
704 if err != nil {
705 c.sendAlert(alertBadCertificate)
706 return errors.New("could not validate signature of connection nonces: " + err.Error())
707 }
708
David Benjamin83c0bc92014-08-04 01:23:53 -0400709 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700710 }
711
David Benjamine098ec22014-08-27 23:13:20 -0400712 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -0700713
714 return nil
715}
716
717func (hs *serverHandshakeState) establishKeys() error {
718 c := hs.c
719
720 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
721 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
722
723 var clientCipher, serverCipher interface{}
724 var clientHash, serverHash macFunction
725
726 if hs.suite.aead == nil {
727 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
728 clientHash = hs.suite.mac(c.vers, clientMAC)
729 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
730 serverHash = hs.suite.mac(c.vers, serverMAC)
731 } else {
732 clientCipher = hs.suite.aead(clientKey, clientIV)
733 serverCipher = hs.suite.aead(serverKey, serverIV)
734 }
735
736 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
737 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
738
739 return nil
740}
741
David Benjamind30a9902014-08-24 01:44:23 -0400742func (hs *serverHandshakeState) readFinished(isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700743 c := hs.c
744
745 c.readRecord(recordTypeChangeCipherSpec)
746 if err := c.in.error(); err != nil {
747 return err
748 }
749
750 if hs.hello.nextProtoNeg {
751 msg, err := c.readHandshake()
752 if err != nil {
753 return err
754 }
755 nextProto, ok := msg.(*nextProtoMsg)
756 if !ok {
757 c.sendAlert(alertUnexpectedMessage)
758 return unexpectedMessageError(nextProto, msg)
759 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400760 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700761 c.clientProtocol = nextProto.proto
762 }
763
David Benjamind30a9902014-08-24 01:44:23 -0400764 if hs.hello.channelIDRequested {
765 msg, err := c.readHandshake()
766 if err != nil {
767 return err
768 }
769 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
770 if !ok {
771 c.sendAlert(alertUnexpectedMessage)
772 return unexpectedMessageError(encryptedExtensions, msg)
773 }
774 x := new(big.Int).SetBytes(encryptedExtensions.channelID[0:32])
775 y := new(big.Int).SetBytes(encryptedExtensions.channelID[32:64])
776 r := new(big.Int).SetBytes(encryptedExtensions.channelID[64:96])
777 s := new(big.Int).SetBytes(encryptedExtensions.channelID[96:128])
778 if !elliptic.P256().IsOnCurve(x, y) {
779 return errors.New("tls: invalid channel ID public key")
780 }
781 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
782 var resumeHash []byte
783 if isResume {
784 resumeHash = hs.sessionState.handshakeHash
785 }
786 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
787 return errors.New("tls: invalid channel ID signature")
788 }
789 c.channelID = channelID
790
791 hs.writeClientHash(encryptedExtensions.marshal())
792 }
793
Adam Langley95c29f32014-06-20 12:00:00 -0700794 msg, err := c.readHandshake()
795 if err != nil {
796 return err
797 }
798 clientFinished, ok := msg.(*finishedMsg)
799 if !ok {
800 c.sendAlert(alertUnexpectedMessage)
801 return unexpectedMessageError(clientFinished, msg)
802 }
803
804 verify := hs.finishedHash.clientSum(hs.masterSecret)
805 if len(verify) != len(clientFinished.verifyData) ||
806 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
807 c.sendAlert(alertHandshakeFailure)
808 return errors.New("tls: client's Finished message is incorrect")
809 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700810 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langley95c29f32014-06-20 12:00:00 -0700811
David Benjamin83c0bc92014-08-04 01:23:53 -0400812 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700813 return nil
814}
815
816func (hs *serverHandshakeState) sendSessionTicket() error {
Adam Langley95c29f32014-06-20 12:00:00 -0700817 c := hs.c
Adam Langley95c29f32014-06-20 12:00:00 -0700818 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -0400819 vers: c.vers,
820 cipherSuite: hs.suite.id,
821 masterSecret: hs.masterSecret,
822 certificates: hs.certsFromClient,
823 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -0700824 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500825
826 if !hs.hello.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
827 if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
828 c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
829 }
830 return nil
831 }
832
833 m := new(newSessionTicketMsg)
834
835 var err error
Adam Langley95c29f32014-06-20 12:00:00 -0700836 m.ticket, err = c.encryptTicket(&state)
837 if err != nil {
838 return err
839 }
Adam Langley95c29f32014-06-20 12:00:00 -0700840
David Benjamin83c0bc92014-08-04 01:23:53 -0400841 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700842 c.writeRecord(recordTypeHandshake, m.marshal())
843
844 return nil
845}
846
847func (hs *serverHandshakeState) sendFinished() error {
848 c := hs.c
849
David Benjamin86271ee2014-07-21 16:14:03 -0400850 finished := new(finishedMsg)
851 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
David Benjamin513f0ea2015-04-02 19:33:31 -0400852 if c.config.Bugs.BadFinished {
853 finished.verifyData[0]++
854 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700855 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -0500856 hs.finishedBytes = finished.marshal()
857 hs.writeServerHash(hs.finishedBytes)
858 postCCSBytes := hs.finishedBytes
David Benjamin86271ee2014-07-21 16:14:03 -0400859
860 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
861 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
862 postCCSBytes = postCCSBytes[5:]
863 }
David Benjamina4e6d482015-03-02 19:10:53 -0500864 c.dtlsFlushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -0400865
David Benjamina0e52232014-07-19 17:39:58 -0400866 if !c.config.Bugs.SkipChangeCipherSpec {
867 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
868 }
Adam Langley95c29f32014-06-20 12:00:00 -0700869
David Benjamin4189bd92015-01-25 23:52:39 -0500870 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
871 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
872 }
David Benjamindc3da932015-03-12 15:09:02 -0400873 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
874 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
875 return errors.New("tls: simulating post-CCS alert")
876 }
David Benjamin4189bd92015-01-25 23:52:39 -0500877
David Benjaminb80168e2015-02-08 18:30:14 -0500878 if !c.config.Bugs.SkipFinished {
879 c.writeRecord(recordTypeHandshake, postCCSBytes)
David Benjamina4e6d482015-03-02 19:10:53 -0500880 c.dtlsFlushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -0500881 }
Adam Langley95c29f32014-06-20 12:00:00 -0700882
883 c.cipherSuite = hs.suite.id
884
885 return nil
886}
887
888// processCertsFromClient takes a chain of client certificates either from a
889// Certificates message or from a sessionState and verifies them. It returns
890// the public key of the leaf certificate.
891func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
892 c := hs.c
893
894 hs.certsFromClient = certificates
895 certs := make([]*x509.Certificate, len(certificates))
896 var err error
897 for i, asn1Data := range certificates {
898 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
899 c.sendAlert(alertBadCertificate)
900 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
901 }
902 }
903
904 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
905 opts := x509.VerifyOptions{
906 Roots: c.config.ClientCAs,
907 CurrentTime: c.config.time(),
908 Intermediates: x509.NewCertPool(),
909 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
910 }
911
912 for _, cert := range certs[1:] {
913 opts.Intermediates.AddCert(cert)
914 }
915
916 chains, err := certs[0].Verify(opts)
917 if err != nil {
918 c.sendAlert(alertBadCertificate)
919 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
920 }
921
922 ok := false
923 for _, ku := range certs[0].ExtKeyUsage {
924 if ku == x509.ExtKeyUsageClientAuth {
925 ok = true
926 break
927 }
928 }
929 if !ok {
930 c.sendAlert(alertHandshakeFailure)
931 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
932 }
933
934 c.verifiedChains = chains
935 }
936
937 if len(certs) > 0 {
938 var pub crypto.PublicKey
939 switch key := certs[0].PublicKey.(type) {
940 case *ecdsa.PublicKey, *rsa.PublicKey:
941 pub = key
942 default:
943 c.sendAlert(alertUnsupportedCertificate)
944 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
945 }
946 c.peerCertificates = certs
947 return pub, nil
948 }
949
950 return nil, nil
951}
952
David Benjamin83c0bc92014-08-04 01:23:53 -0400953func (hs *serverHandshakeState) writeServerHash(msg []byte) {
954 // writeServerHash is called before writeRecord.
955 hs.writeHash(msg, hs.c.sendHandshakeSeq)
956}
957
958func (hs *serverHandshakeState) writeClientHash(msg []byte) {
959 // writeClientHash is called after readHandshake.
960 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
961}
962
963func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
964 if hs.c.isDTLS {
965 // This is somewhat hacky. DTLS hashes a slightly different format.
966 // First, the TLS header.
967 hs.finishedHash.Write(msg[:4])
968 // Then the sequence number and reassembled fragment offset (always 0).
969 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
970 // Then the reassembled fragment (always equal to the message length).
971 hs.finishedHash.Write(msg[1:4])
972 // And then the message body.
973 hs.finishedHash.Write(msg[4:])
974 } else {
975 hs.finishedHash.Write(msg)
976 }
977}
978
Adam Langley95c29f32014-06-20 12:00:00 -0700979// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
980// is acceptable to use.
981func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
982 for _, supported := range supportedCipherSuites {
983 if id == supported {
984 var candidate *cipherSuite
985
986 for _, s := range cipherSuites {
987 if s.id == id {
988 candidate = s
989 break
990 }
991 }
992 if candidate == nil {
993 continue
994 }
995 // Don't select a ciphersuite which we can't
996 // support for this client.
997 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
998 continue
999 }
1000 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
1001 continue
1002 }
David Benjamin39ebf532014-08-31 02:23:49 -04001003 if !c.config.Bugs.SkipCipherVersionCheck && version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
Adam Langley95c29f32014-06-20 12:00:00 -07001004 continue
1005 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001006 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
1007 continue
1008 }
Adam Langley95c29f32014-06-20 12:00:00 -07001009 return candidate
1010 }
1011 }
1012
1013 return nil
1014}