blob: af521fc53c157d63b6df4173a7cd114f98ceec7c [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.
78 if err := c.simulatePacketLoss(func() { c.writeRecord(recordTypeHandshake, hs.finishedBytes) }); err != nil {
79 return err
80 }
David Benjamind30a9902014-08-24 01:44:23 -040081 if err := hs.readFinished(isResume); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -070082 return err
83 }
84 c.didResume = true
85 } else {
86 // The client didn't include a session ticket, or it wasn't
87 // valid so we do a full handshake.
88 if err := hs.doFullHandshake(); err != nil {
89 return err
90 }
91 if err := hs.establishKeys(); err != nil {
92 return err
93 }
David Benjamind30a9902014-08-24 01:44:23 -040094 if err := hs.readFinished(isResume); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -070095 return err
96 }
David Benjamine58c4f52014-08-24 03:47:07 -040097 if c.config.Bugs.ExpectFalseStart {
98 if err := c.readRecord(recordTypeApplicationData); err != nil {
99 return err
100 }
101 }
Adam Langley95c29f32014-06-20 12:00:00 -0700102 if err := hs.sendSessionTicket(); err != nil {
103 return err
104 }
105 if err := hs.sendFinished(); err != nil {
106 return err
107 }
108 }
109 c.handshakeComplete = true
110
111 return nil
112}
113
114// readClientHello reads a ClientHello message from the client and decides
115// whether we will perform session resumption.
116func (hs *serverHandshakeState) readClientHello() (isResume bool, err error) {
117 config := hs.c.config
118 c := hs.c
119
David Benjamin83f90402015-01-27 01:09:43 -0500120 if err := c.simulatePacketLoss(nil); err != nil {
121 return false, err
122 }
Adam Langley95c29f32014-06-20 12:00:00 -0700123 msg, err := c.readHandshake()
124 if err != nil {
125 return false, err
126 }
127 var ok bool
128 hs.clientHello, ok = msg.(*clientHelloMsg)
129 if !ok {
130 c.sendAlert(alertUnexpectedMessage)
131 return false, unexpectedMessageError(hs.clientHello, msg)
132 }
Feng Lu41aa3252014-11-21 22:47:56 -0800133 if config.Bugs.RequireFastradioPadding && len(hs.clientHello.raw) < 1000 {
134 return false, errors.New("tls: ClientHello record size should be larger than 1000 bytes when padding enabled.")
135 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400136
137 if c.isDTLS && !config.Bugs.SkipHelloVerifyRequest {
David Benjamin8bc38f52014-08-16 12:07:27 -0400138 // Per RFC 6347, the version field in HelloVerifyRequest SHOULD
139 // be always DTLS 1.0
David Benjamin83c0bc92014-08-04 01:23:53 -0400140 helloVerifyRequest := &helloVerifyRequestMsg{
David Benjamin8bc38f52014-08-16 12:07:27 -0400141 vers: VersionTLS10,
David Benjamin83c0bc92014-08-04 01:23:53 -0400142 cookie: make([]byte, 32),
143 }
144 if _, err := io.ReadFull(c.config.rand(), helloVerifyRequest.cookie); err != nil {
145 c.sendAlert(alertInternalError)
146 return false, errors.New("dtls: short read from Rand: " + err.Error())
147 }
148 c.writeRecord(recordTypeHandshake, helloVerifyRequest.marshal())
149
David Benjamin83f90402015-01-27 01:09:43 -0500150 if err := c.simulatePacketLoss(nil); err != nil {
151 return false, err
152 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400153 msg, err := c.readHandshake()
154 if err != nil {
155 return false, err
156 }
157 newClientHello, ok := msg.(*clientHelloMsg)
158 if !ok {
159 c.sendAlert(alertUnexpectedMessage)
160 return false, unexpectedMessageError(hs.clientHello, msg)
161 }
162 if !bytes.Equal(newClientHello.cookie, helloVerifyRequest.cookie) {
163 return false, errors.New("dtls: invalid cookie")
164 }
David Benjaminf2fedef2014-08-16 01:37:34 -0400165
166 // Apart from the cookie, the two ClientHellos must
167 // match. Note that clientHello.equal compares the
168 // serialization, so we make a copy.
169 oldClientHelloCopy := *hs.clientHello
170 oldClientHelloCopy.raw = nil
171 oldClientHelloCopy.cookie = nil
172 newClientHelloCopy := *newClientHello
173 newClientHelloCopy.raw = nil
174 newClientHelloCopy.cookie = nil
175 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400176 return false, errors.New("dtls: retransmitted ClientHello does not match")
177 }
178 hs.clientHello = newClientHello
179 }
180
David Benjaminc44b1df2014-11-23 12:11:01 -0500181 if config.Bugs.RequireSameRenegoClientVersion && c.clientVersion != 0 {
182 if c.clientVersion != hs.clientHello.vers {
183 return false, fmt.Errorf("tls: client offered different version on renego")
184 }
185 }
186 c.clientVersion = hs.clientHello.vers
187
David Benjamin6ae7f072015-01-26 10:22:13 -0500188 // Reject < 1.2 ClientHellos with signature_algorithms.
189 if c.clientVersion < VersionTLS12 && len(hs.clientHello.signatureAndHashes) > 0 {
190 return false, fmt.Errorf("tls: client included signature_algorithms before TLS 1.2")
191 }
192
David Benjamin8bc38f52014-08-16 12:07:27 -0400193 c.vers, ok = config.mutualVersion(hs.clientHello.vers)
194 if !ok {
195 c.sendAlert(alertProtocolVersion)
196 return false, fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
197 }
Adam Langley95c29f32014-06-20 12:00:00 -0700198 c.haveVers = true
199
200 hs.hello = new(serverHelloMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400201 hs.hello.isDTLS = c.isDTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700202
203 supportedCurve := false
204 preferredCurves := config.curvePreferences()
205Curves:
206 for _, curve := range hs.clientHello.supportedCurves {
207 for _, supported := range preferredCurves {
208 if supported == curve {
209 supportedCurve = true
210 break Curves
211 }
212 }
213 }
214
215 supportedPointFormat := false
216 for _, pointFormat := range hs.clientHello.supportedPoints {
217 if pointFormat == pointFormatUncompressed {
218 supportedPointFormat = true
219 break
220 }
221 }
222 hs.ellipticOk = supportedCurve && supportedPointFormat
223
224 foundCompression := false
225 // We only support null compression, so check that the client offered it.
226 for _, compression := range hs.clientHello.compressionMethods {
227 if compression == compressionNone {
228 foundCompression = true
229 break
230 }
231 }
232
233 if !foundCompression {
234 c.sendAlert(alertHandshakeFailure)
235 return false, errors.New("tls: client does not support uncompressed connections")
236 }
237
238 hs.hello.vers = c.vers
239 hs.hello.random = make([]byte, 32)
240 _, err = io.ReadFull(config.rand(), hs.hello.random)
241 if err != nil {
242 c.sendAlert(alertInternalError)
243 return false, err
244 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700245
Adam Langleycf2d4f42014-10-28 19:06:14 -0700246 if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) {
Adam Langley2ae77d22014-10-28 17:29:33 -0700247 c.sendAlert(alertHandshakeFailure)
Adam Langleycf2d4f42014-10-28 19:06:14 -0700248 return false, errors.New("tls: renegotiation mismatch")
Adam Langley2ae77d22014-10-28 17:29:33 -0700249 }
Adam Langleycf2d4f42014-10-28 19:06:14 -0700250
251 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
252 hs.hello.secureRenegotiation = append(hs.hello.secureRenegotiation, c.clientVerify...)
253 hs.hello.secureRenegotiation = append(hs.hello.secureRenegotiation, c.serverVerify...)
254 if c.config.Bugs.BadRenegotiationInfo {
255 hs.hello.secureRenegotiation[0] ^= 0x80
256 }
257 } else {
258 hs.hello.secureRenegotiation = hs.clientHello.secureRenegotiation
259 }
260
Adam Langley95c29f32014-06-20 12:00:00 -0700261 hs.hello.compressionMethod = compressionNone
David Benjamin35a7a442014-07-05 00:23:20 -0400262 hs.hello.duplicateExtension = c.config.Bugs.DuplicateExtension
Adam Langley95c29f32014-06-20 12:00:00 -0700263 if len(hs.clientHello.serverName) > 0 {
264 c.serverName = hs.clientHello.serverName
265 }
David Benjaminfa055a22014-09-15 16:51:51 -0400266
267 if len(hs.clientHello.alpnProtocols) > 0 {
268 if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
269 hs.hello.alpnProtocol = selectedProto
270 c.clientProtocol = selectedProto
David Benjaminfc7b0862014-09-06 13:21:53 -0400271 c.usedALPN = true
David Benjaminfa055a22014-09-15 16:51:51 -0400272 }
273 } else {
274 // Although sending an empty NPN extension is reasonable, Firefox has
275 // had a bug around this. Best to send nothing at all if
276 // config.NextProtos is empty. See
277 // https://code.google.com/p/go/issues/detail?id=5445.
278 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
279 hs.hello.nextProtoNeg = true
280 hs.hello.nextProtos = config.NextProtos
281 }
Adam Langley95c29f32014-06-20 12:00:00 -0700282 }
Adam Langley75712922014-10-10 16:23:43 -0700283 hs.hello.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !c.config.Bugs.NoExtendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700284
285 if len(config.Certificates) == 0 {
286 c.sendAlert(alertInternalError)
287 return false, errors.New("tls: no certificates configured")
288 }
289 hs.cert = &config.Certificates[0]
290 if len(hs.clientHello.serverName) > 0 {
291 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
292 }
David Benjamine78bfde2014-09-06 12:45:15 -0400293 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
294 return false, errors.New("tls: unexpected server name")
295 }
Adam Langley95c29f32014-06-20 12:00:00 -0700296
David Benjamind30a9902014-08-24 01:44:23 -0400297 if hs.clientHello.channelIDSupported && config.RequestChannelID {
298 hs.hello.channelIDRequested = true
299 }
300
David Benjaminca6c8262014-11-15 19:06:08 -0500301 if hs.clientHello.srtpProtectionProfiles != nil {
302 SRTPLoop:
303 for _, p1 := range c.config.SRTPProtectionProfiles {
304 for _, p2 := range hs.clientHello.srtpProtectionProfiles {
305 if p1 == p2 {
306 hs.hello.srtpProtectionProfile = p1
307 c.srtpProtectionProfile = p1
308 break SRTPLoop
309 }
310 }
311 }
312 }
313
314 if c.config.Bugs.SendSRTPProtectionProfile != 0 {
315 hs.hello.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
316 }
317
Adam Langley95c29f32014-06-20 12:00:00 -0700318 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
319
320 if hs.checkForResumption() {
321 return true, nil
322 }
323
Adam Langleyac61fa32014-06-23 12:03:11 -0700324 var scsvFound bool
325
326 for _, cipherSuite := range hs.clientHello.cipherSuites {
327 if cipherSuite == fallbackSCSV {
328 scsvFound = true
329 break
330 }
331 }
332
333 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
334 return false, errors.New("tls: no fallback SCSV found when expected")
335 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
336 return false, errors.New("tls: fallback SCSV found when not expected")
337 }
338
Adam Langley95c29f32014-06-20 12:00:00 -0700339 var preferenceList, supportedList []uint16
340 if c.config.PreferServerCipherSuites {
341 preferenceList = c.config.cipherSuites()
342 supportedList = hs.clientHello.cipherSuites
343 } else {
344 preferenceList = hs.clientHello.cipherSuites
345 supportedList = c.config.cipherSuites()
346 }
347
348 for _, id := range preferenceList {
349 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
350 break
351 }
352 }
353
354 if hs.suite == nil {
355 c.sendAlert(alertHandshakeFailure)
356 return false, errors.New("tls: no cipher suite supported by both client and server")
357 }
358
359 return false, nil
360}
361
362// checkForResumption returns true if we should perform resumption on this connection.
363func (hs *serverHandshakeState) checkForResumption() bool {
364 c := hs.c
365
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500366 if len(hs.clientHello.sessionTicket) > 0 {
367 if c.config.SessionTicketsDisabled {
368 return false
369 }
David Benjaminb0c8db72014-09-24 15:19:56 -0400370
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500371 var ok bool
372 if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
373 return false
374 }
375 } else {
376 if c.config.ServerSessionCache == nil {
377 return false
378 }
379
380 var ok bool
381 sessionId := string(hs.clientHello.sessionId)
382 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
383 return false
384 }
Adam Langley95c29f32014-06-20 12:00:00 -0700385 }
386
David Benjamine18d8212014-11-10 02:37:15 -0500387 // Never resume a session for a different SSL version.
388 if !c.config.Bugs.AllowSessionVersionMismatch && c.vers != hs.sessionState.vers {
389 return false
Adam Langley95c29f32014-06-20 12:00:00 -0700390 }
391
392 cipherSuiteOk := false
393 // Check that the client is still offering the ciphersuite in the session.
394 for _, id := range hs.clientHello.cipherSuites {
395 if id == hs.sessionState.cipherSuite {
396 cipherSuiteOk = true
397 break
398 }
399 }
400 if !cipherSuiteOk {
401 return false
402 }
403
404 // Check that we also support the ciphersuite from the session.
405 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk)
406 if hs.suite == nil {
407 return false
408 }
409
410 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
411 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
412 if needClientCerts && !sessionHasClientCerts {
413 return false
414 }
415 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
416 return false
417 }
418
419 return true
420}
421
422func (hs *serverHandshakeState) doResumeHandshake() error {
423 c := hs.c
424
425 hs.hello.cipherSuite = hs.suite.id
426 // We echo the client's session ID in the ServerHello to let it know
427 // that we're doing a resumption.
428 hs.hello.sessionId = hs.clientHello.sessionId
David Benjaminbed9aae2014-08-07 19:13:38 -0400429 hs.hello.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -0700430
431 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -0400432 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -0400433 hs.writeClientHash(hs.clientHello.marshal())
434 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700435
436 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
437
438 if len(hs.sessionState.certificates) > 0 {
439 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
440 return err
441 }
442 }
443
444 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -0700445 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700446
447 return nil
448}
449
450func (hs *serverHandshakeState) doFullHandshake() error {
451 config := hs.c.config
452 c := hs.c
453
David Benjamin48cae082014-10-27 01:06:24 -0400454 isPSK := hs.suite.flags&suitePSK != 0
455 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700456 hs.hello.ocspStapling = true
457 }
458
David Benjamin61f95272014-11-25 01:55:35 -0500459 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
460 hs.hello.sctList = hs.cert.SignedCertificateTimestampList
461 }
462
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500463 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
Adam Langley95c29f32014-06-20 12:00:00 -0700464 hs.hello.cipherSuite = hs.suite.id
David Benjamin6095de82014-12-27 01:50:38 -0500465 if config.Bugs.SendCipherSuite != 0 {
466 hs.hello.cipherSuite = config.Bugs.SendCipherSuite
467 }
Adam Langley75712922014-10-10 16:23:43 -0700468 c.extendedMasterSecret = hs.hello.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700469
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500470 // Generate a session ID if we're to save the session.
471 if !hs.hello.ticketSupported && config.ServerSessionCache != nil {
472 hs.hello.sessionId = make([]byte, 32)
473 if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
474 c.sendAlert(alertInternalError)
475 return errors.New("tls: short read from Rand: " + err.Error())
476 }
477 }
478
Adam Langley95c29f32014-06-20 12:00:00 -0700479 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -0400480 hs.writeClientHash(hs.clientHello.marshal())
481 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700482
483 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
484
David Benjamin48cae082014-10-27 01:06:24 -0400485 if !isPSK {
486 certMsg := new(certificateMsg)
487 certMsg.certificates = hs.cert.Certificate
488 if !config.Bugs.UnauthenticatedECDH {
489 hs.writeServerHash(certMsg.marshal())
490 c.writeRecord(recordTypeHandshake, certMsg.marshal())
491 }
David Benjamin1c375dd2014-07-12 00:48:23 -0400492 }
Adam Langley95c29f32014-06-20 12:00:00 -0700493
494 if hs.hello.ocspStapling {
495 certStatus := new(certificateStatusMsg)
496 certStatus.statusType = statusTypeOCSP
497 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -0400498 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700499 c.writeRecord(recordTypeHandshake, certStatus.marshal())
500 }
501
502 keyAgreement := hs.suite.ka(c.vers)
503 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
504 if err != nil {
505 c.sendAlert(alertHandshakeFailure)
506 return err
507 }
David Benjamin9c651c92014-07-12 13:27:45 -0400508 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -0400509 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700510 c.writeRecord(recordTypeHandshake, skx.marshal())
511 }
512
513 if config.ClientAuth >= RequestClientCert {
514 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -0400515 certReq := &certificateRequestMsg{
516 certificateTypes: config.ClientCertificateTypes,
517 }
518 if certReq.certificateTypes == nil {
519 certReq.certificateTypes = []byte{
520 byte(CertTypeRSASign),
521 byte(CertTypeECDSASign),
522 }
Adam Langley95c29f32014-06-20 12:00:00 -0700523 }
524 if c.vers >= VersionTLS12 {
525 certReq.hasSignatureAndHash = true
David Benjamin000800a2014-11-14 01:43:59 -0500526 if !config.Bugs.NoSignatureAndHashes {
527 certReq.signatureAndHashes = config.signatureAndHashesForServer()
528 }
Adam Langley95c29f32014-06-20 12:00:00 -0700529 }
530
531 // An empty list of certificateAuthorities signals to
532 // the client that it may send any certificate in response
533 // to our request. When we know the CAs we trust, then
534 // we can send them down, so that the client can choose
535 // an appropriate certificate to give to us.
536 if config.ClientCAs != nil {
537 certReq.certificateAuthorities = config.ClientCAs.Subjects()
538 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400539 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700540 c.writeRecord(recordTypeHandshake, certReq.marshal())
541 }
542
543 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400544 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700545 c.writeRecord(recordTypeHandshake, helloDone.marshal())
546
547 var pub crypto.PublicKey // public key for client auth, if any
548
David Benjamin83f90402015-01-27 01:09:43 -0500549 if err := c.simulatePacketLoss(nil); err != nil {
550 return err
551 }
Adam Langley95c29f32014-06-20 12:00:00 -0700552 msg, err := c.readHandshake()
553 if err != nil {
554 return err
555 }
556
557 var ok bool
558 // If we requested a client certificate, then the client must send a
559 // certificate message, even if it's empty.
560 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -0400561 var certMsg *certificateMsg
Adam Langley95c29f32014-06-20 12:00:00 -0700562 if certMsg, ok = msg.(*certificateMsg); !ok {
563 c.sendAlert(alertUnexpectedMessage)
564 return unexpectedMessageError(certMsg, msg)
565 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400566 hs.writeClientHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700567
568 if len(certMsg.certificates) == 0 {
569 // The client didn't actually send a certificate
570 switch config.ClientAuth {
571 case RequireAnyClientCert, RequireAndVerifyClientCert:
572 c.sendAlert(alertBadCertificate)
573 return errors.New("tls: client didn't provide a certificate")
574 }
575 }
576
577 pub, err = hs.processCertsFromClient(certMsg.certificates)
578 if err != nil {
579 return err
580 }
581
582 msg, err = c.readHandshake()
583 if err != nil {
584 return err
585 }
586 }
587
588 // Get client key exchange
589 ckx, ok := msg.(*clientKeyExchangeMsg)
590 if !ok {
591 c.sendAlert(alertUnexpectedMessage)
592 return unexpectedMessageError(ckx, msg)
593 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400594 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700595
David Benjamine098ec22014-08-27 23:13:20 -0400596 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
597 if err != nil {
598 c.sendAlert(alertHandshakeFailure)
599 return err
600 }
Adam Langley75712922014-10-10 16:23:43 -0700601 if c.extendedMasterSecret {
602 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
603 } else {
604 if c.config.Bugs.RequireExtendedMasterSecret {
605 return errors.New("tls: extended master secret required but not supported by peer")
606 }
607 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
608 }
David Benjamine098ec22014-08-27 23:13:20 -0400609
Adam Langley95c29f32014-06-20 12:00:00 -0700610 // If we received a client cert in response to our certificate request message,
611 // the client will send us a certificateVerifyMsg immediately after the
612 // clientKeyExchangeMsg. This message is a digest of all preceding
613 // handshake-layer messages that is signed using the private key corresponding
614 // to the client's certificate. This allows us to verify that the client is in
615 // possession of the private key of the certificate.
616 if len(c.peerCertificates) > 0 {
617 msg, err = c.readHandshake()
618 if err != nil {
619 return err
620 }
621 certVerify, ok := msg.(*certificateVerifyMsg)
622 if !ok {
623 c.sendAlert(alertUnexpectedMessage)
624 return unexpectedMessageError(certVerify, msg)
625 }
626
David Benjaminde620d92014-07-18 15:03:41 -0400627 // Determine the signature type.
628 var signatureAndHash signatureAndHash
629 if certVerify.hasSignatureAndHash {
630 signatureAndHash = certVerify.signatureAndHash
David Benjamin000800a2014-11-14 01:43:59 -0500631 if !isSupportedSignatureAndHash(signatureAndHash, config.signatureAndHashesForServer()) {
632 return errors.New("tls: unsupported hash function for client certificate")
633 }
David Benjaminde620d92014-07-18 15:03:41 -0400634 } else {
635 // Before TLS 1.2 the signature algorithm was implicit
636 // from the key type, and only one hash per signature
637 // algorithm was possible. Leave the hash as zero.
638 switch pub.(type) {
639 case *ecdsa.PublicKey:
640 signatureAndHash.signature = signatureECDSA
641 case *rsa.PublicKey:
642 signatureAndHash.signature = signatureRSA
643 }
644 }
645
Adam Langley95c29f32014-06-20 12:00:00 -0700646 switch key := pub.(type) {
647 case *ecdsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400648 if signatureAndHash.signature != signatureECDSA {
649 err = errors.New("tls: bad signature type for client's ECDSA certificate")
650 break
651 }
Adam Langley95c29f32014-06-20 12:00:00 -0700652 ecdsaSig := new(ecdsaSignature)
653 if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {
654 break
655 }
656 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
657 err = errors.New("ECDSA signature contained zero or negative values")
658 break
659 }
David Benjaminde620d92014-07-18 15:03:41 -0400660 var digest []byte
David Benjamine098ec22014-08-27 23:13:20 -0400661 digest, _, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400662 if err != nil {
663 break
664 }
Adam Langley95c29f32014-06-20 12:00:00 -0700665 if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {
666 err = errors.New("ECDSA verification failure")
667 break
668 }
669 case *rsa.PublicKey:
David Benjaminde620d92014-07-18 15:03:41 -0400670 if signatureAndHash.signature != signatureRSA {
671 err = errors.New("tls: bad signature type for client's RSA certificate")
672 break
673 }
674 var digest []byte
675 var hashFunc crypto.Hash
David Benjamine098ec22014-08-27 23:13:20 -0400676 digest, hashFunc, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
David Benjaminde620d92014-07-18 15:03:41 -0400677 if err != nil {
678 break
679 }
Adam Langley95c29f32014-06-20 12:00:00 -0700680 err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)
681 }
682 if err != nil {
683 c.sendAlert(alertBadCertificate)
684 return errors.New("could not validate signature of connection nonces: " + err.Error())
685 }
686
David Benjamin83c0bc92014-08-04 01:23:53 -0400687 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700688 }
689
David Benjamine098ec22014-08-27 23:13:20 -0400690 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -0700691
692 return nil
693}
694
695func (hs *serverHandshakeState) establishKeys() error {
696 c := hs.c
697
698 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
699 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
700
701 var clientCipher, serverCipher interface{}
702 var clientHash, serverHash macFunction
703
704 if hs.suite.aead == nil {
705 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
706 clientHash = hs.suite.mac(c.vers, clientMAC)
707 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
708 serverHash = hs.suite.mac(c.vers, serverMAC)
709 } else {
710 clientCipher = hs.suite.aead(clientKey, clientIV)
711 serverCipher = hs.suite.aead(serverKey, serverIV)
712 }
713
714 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
715 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
716
717 return nil
718}
719
David Benjamind30a9902014-08-24 01:44:23 -0400720func (hs *serverHandshakeState) readFinished(isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700721 c := hs.c
722
723 c.readRecord(recordTypeChangeCipherSpec)
724 if err := c.in.error(); err != nil {
725 return err
726 }
727
728 if hs.hello.nextProtoNeg {
729 msg, err := c.readHandshake()
730 if err != nil {
731 return err
732 }
733 nextProto, ok := msg.(*nextProtoMsg)
734 if !ok {
735 c.sendAlert(alertUnexpectedMessage)
736 return unexpectedMessageError(nextProto, msg)
737 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400738 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700739 c.clientProtocol = nextProto.proto
740 }
741
David Benjamind30a9902014-08-24 01:44:23 -0400742 if hs.hello.channelIDRequested {
743 msg, err := c.readHandshake()
744 if err != nil {
745 return err
746 }
747 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
748 if !ok {
749 c.sendAlert(alertUnexpectedMessage)
750 return unexpectedMessageError(encryptedExtensions, msg)
751 }
752 x := new(big.Int).SetBytes(encryptedExtensions.channelID[0:32])
753 y := new(big.Int).SetBytes(encryptedExtensions.channelID[32:64])
754 r := new(big.Int).SetBytes(encryptedExtensions.channelID[64:96])
755 s := new(big.Int).SetBytes(encryptedExtensions.channelID[96:128])
756 if !elliptic.P256().IsOnCurve(x, y) {
757 return errors.New("tls: invalid channel ID public key")
758 }
759 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
760 var resumeHash []byte
761 if isResume {
762 resumeHash = hs.sessionState.handshakeHash
763 }
764 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
765 return errors.New("tls: invalid channel ID signature")
766 }
767 c.channelID = channelID
768
769 hs.writeClientHash(encryptedExtensions.marshal())
770 }
771
Adam Langley95c29f32014-06-20 12:00:00 -0700772 msg, err := c.readHandshake()
773 if err != nil {
774 return err
775 }
776 clientFinished, ok := msg.(*finishedMsg)
777 if !ok {
778 c.sendAlert(alertUnexpectedMessage)
779 return unexpectedMessageError(clientFinished, msg)
780 }
781
782 verify := hs.finishedHash.clientSum(hs.masterSecret)
783 if len(verify) != len(clientFinished.verifyData) ||
784 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
785 c.sendAlert(alertHandshakeFailure)
786 return errors.New("tls: client's Finished message is incorrect")
787 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700788 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langley95c29f32014-06-20 12:00:00 -0700789
David Benjamin83c0bc92014-08-04 01:23:53 -0400790 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700791 return nil
792}
793
794func (hs *serverHandshakeState) sendSessionTicket() error {
Adam Langley95c29f32014-06-20 12:00:00 -0700795 c := hs.c
Adam Langley95c29f32014-06-20 12:00:00 -0700796 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -0400797 vers: c.vers,
798 cipherSuite: hs.suite.id,
799 masterSecret: hs.masterSecret,
800 certificates: hs.certsFromClient,
801 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -0700802 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500803
804 if !hs.hello.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
805 if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
806 c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
807 }
808 return nil
809 }
810
811 m := new(newSessionTicketMsg)
812
813 var err error
Adam Langley95c29f32014-06-20 12:00:00 -0700814 m.ticket, err = c.encryptTicket(&state)
815 if err != nil {
816 return err
817 }
Adam Langley95c29f32014-06-20 12:00:00 -0700818
David Benjamin83c0bc92014-08-04 01:23:53 -0400819 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700820 c.writeRecord(recordTypeHandshake, m.marshal())
821
822 return nil
823}
824
825func (hs *serverHandshakeState) sendFinished() error {
826 c := hs.c
827
David Benjamin86271ee2014-07-21 16:14:03 -0400828 finished := new(finishedMsg)
829 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
Adam Langley2ae77d22014-10-28 17:29:33 -0700830 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -0500831 hs.finishedBytes = finished.marshal()
832 hs.writeServerHash(hs.finishedBytes)
833 postCCSBytes := hs.finishedBytes
David Benjamin86271ee2014-07-21 16:14:03 -0400834
835 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
836 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
837 postCCSBytes = postCCSBytes[5:]
838 }
839
David Benjamina0e52232014-07-19 17:39:58 -0400840 if !c.config.Bugs.SkipChangeCipherSpec {
841 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
842 }
Adam Langley95c29f32014-06-20 12:00:00 -0700843
David Benjamin4189bd92015-01-25 23:52:39 -0500844 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
845 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
846 }
847
David Benjamin86271ee2014-07-21 16:14:03 -0400848 c.writeRecord(recordTypeHandshake, postCCSBytes)
Adam Langley95c29f32014-06-20 12:00:00 -0700849
850 c.cipherSuite = hs.suite.id
851
852 return nil
853}
854
855// processCertsFromClient takes a chain of client certificates either from a
856// Certificates message or from a sessionState and verifies them. It returns
857// the public key of the leaf certificate.
858func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
859 c := hs.c
860
861 hs.certsFromClient = certificates
862 certs := make([]*x509.Certificate, len(certificates))
863 var err error
864 for i, asn1Data := range certificates {
865 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
866 c.sendAlert(alertBadCertificate)
867 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
868 }
869 }
870
871 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
872 opts := x509.VerifyOptions{
873 Roots: c.config.ClientCAs,
874 CurrentTime: c.config.time(),
875 Intermediates: x509.NewCertPool(),
876 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
877 }
878
879 for _, cert := range certs[1:] {
880 opts.Intermediates.AddCert(cert)
881 }
882
883 chains, err := certs[0].Verify(opts)
884 if err != nil {
885 c.sendAlert(alertBadCertificate)
886 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
887 }
888
889 ok := false
890 for _, ku := range certs[0].ExtKeyUsage {
891 if ku == x509.ExtKeyUsageClientAuth {
892 ok = true
893 break
894 }
895 }
896 if !ok {
897 c.sendAlert(alertHandshakeFailure)
898 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
899 }
900
901 c.verifiedChains = chains
902 }
903
904 if len(certs) > 0 {
905 var pub crypto.PublicKey
906 switch key := certs[0].PublicKey.(type) {
907 case *ecdsa.PublicKey, *rsa.PublicKey:
908 pub = key
909 default:
910 c.sendAlert(alertUnsupportedCertificate)
911 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
912 }
913 c.peerCertificates = certs
914 return pub, nil
915 }
916
917 return nil, nil
918}
919
David Benjamin83c0bc92014-08-04 01:23:53 -0400920func (hs *serverHandshakeState) writeServerHash(msg []byte) {
921 // writeServerHash is called before writeRecord.
922 hs.writeHash(msg, hs.c.sendHandshakeSeq)
923}
924
925func (hs *serverHandshakeState) writeClientHash(msg []byte) {
926 // writeClientHash is called after readHandshake.
927 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
928}
929
930func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
931 if hs.c.isDTLS {
932 // This is somewhat hacky. DTLS hashes a slightly different format.
933 // First, the TLS header.
934 hs.finishedHash.Write(msg[:4])
935 // Then the sequence number and reassembled fragment offset (always 0).
936 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
937 // Then the reassembled fragment (always equal to the message length).
938 hs.finishedHash.Write(msg[1:4])
939 // And then the message body.
940 hs.finishedHash.Write(msg[4:])
941 } else {
942 hs.finishedHash.Write(msg)
943 }
944}
945
Adam Langley95c29f32014-06-20 12:00:00 -0700946// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
947// is acceptable to use.
948func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
949 for _, supported := range supportedCipherSuites {
950 if id == supported {
951 var candidate *cipherSuite
952
953 for _, s := range cipherSuites {
954 if s.id == id {
955 candidate = s
956 break
957 }
958 }
959 if candidate == nil {
960 continue
961 }
962 // Don't select a ciphersuite which we can't
963 // support for this client.
964 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
965 continue
966 }
967 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
968 continue
969 }
David Benjamin39ebf532014-08-31 02:23:49 -0400970 if !c.config.Bugs.SkipCipherVersionCheck && version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700971 continue
972 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400973 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
974 continue
975 }
Adam Langley95c29f32014-06-20 12:00:00 -0700976 return candidate
977 }
978 }
979
980 return nil
981}