blob: 56c49d9cdcce8ce0f0bd5ecb33354c11eb34171f [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
Adam Langleydc7e9c42015-09-29 15:21:04 -07005package runner
Adam Langley95c29f32014-06-20 12:00:00 -07006
7import (
8 "bytes"
Nick Harper60edffd2016-06-21 15:19:24 -07009 "crypto"
Adam Langley95c29f32014-06-20 12:00:00 -070010 "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"
Adam Langley95c29f32014-06-20 12:00:00 -070015 "errors"
16 "fmt"
17 "io"
David Benjaminde620d92014-07-18 15:03:41 -040018 "math/big"
Adam Langley95c29f32014-06-20 12:00:00 -070019 "net"
20 "strconv"
21)
22
23type clientHandshakeState struct {
David Benjamin83f90402015-01-27 01:09:43 -050024 c *Conn
25 serverHello *serverHelloMsg
26 hello *clientHelloMsg
27 suite *cipherSuite
28 finishedHash finishedHash
Nick Harperb41d2e42016-07-01 17:50:32 -040029 keyShares map[CurveID]ecdhCurve
David Benjamin83f90402015-01-27 01:09:43 -050030 masterSecret []byte
31 session *ClientSessionState
32 finishedBytes []byte
Adam Langley95c29f32014-06-20 12:00:00 -070033}
34
35func (c *Conn) clientHandshake() error {
36 if c.config == nil {
37 c.config = defaultConfig()
38 }
39
40 if len(c.config.ServerName) == 0 && !c.config.InsecureSkipVerify {
41 return errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
42 }
43
David Benjamin83c0bc92014-08-04 01:23:53 -040044 c.sendHandshakeSeq = 0
45 c.recvHandshakeSeq = 0
46
David Benjaminfa055a22014-09-15 16:51:51 -040047 nextProtosLength := 0
48 for _, proto := range c.config.NextProtos {
Adam Langleyefb0e162015-07-09 11:35:04 -070049 if l := len(proto); l > 255 {
David Benjaminfa055a22014-09-15 16:51:51 -040050 return errors.New("tls: invalid NextProtos value")
51 } else {
52 nextProtosLength += 1 + l
53 }
54 }
55 if nextProtosLength > 0xffff {
56 return errors.New("tls: NextProtos values too large")
57 }
58
Adam Langley95c29f32014-06-20 12:00:00 -070059 hello := &clientHelloMsg{
David Benjaminca6c8262014-11-15 19:06:08 -050060 isDTLS: c.isDTLS,
David Benjamincecee272016-06-30 13:33:47 -040061 vers: c.config.maxVersion(c.isDTLS),
David Benjaminca6c8262014-11-15 19:06:08 -050062 compressionMethods: []uint8{compressionNone},
63 random: make([]byte, 32),
64 ocspStapling: true,
Paul Lietar4fac72e2015-09-09 13:44:55 +010065 sctListSupported: true,
David Benjaminca6c8262014-11-15 19:06:08 -050066 serverName: c.config.ServerName,
67 supportedCurves: c.config.curvePreferences(),
68 supportedPoints: []uint8{pointFormatUncompressed},
69 nextProtoNeg: len(c.config.NextProtos) > 0,
70 secureRenegotiation: []byte{},
71 alpnProtocols: c.config.NextProtos,
72 duplicateExtension: c.config.Bugs.DuplicateExtension,
73 channelIDSupported: c.config.ChannelID != nil,
74 npnLast: c.config.Bugs.SwapNPNAndALPN,
David Benjamincecee272016-06-30 13:33:47 -040075 extendedMasterSecret: c.config.maxVersion(c.isDTLS) >= VersionTLS10,
David Benjaminca6c8262014-11-15 19:06:08 -050076 srtpProtectionProfiles: c.config.SRTPProtectionProfiles,
77 srtpMasterKeyIdentifier: c.config.Bugs.SRTPMasterKeyIdentifer,
Adam Langley09505632015-07-30 18:10:13 -070078 customExtension: c.config.Bugs.CustomExtension,
Adam Langley95c29f32014-06-20 12:00:00 -070079 }
80
David Benjamin98e882e2014-08-08 13:24:34 -040081 if c.config.Bugs.SendClientVersion != 0 {
82 hello.vers = c.config.Bugs.SendClientVersion
83 }
84
Adam Langley75712922014-10-10 16:23:43 -070085 if c.config.Bugs.NoExtendedMasterSecret {
86 hello.extendedMasterSecret = false
87 }
88
David Benjamin55a43642015-04-20 14:45:55 -040089 if c.config.Bugs.NoSupportedCurves {
90 hello.supportedCurves = nil
91 }
92
Adam Langley2ae77d22014-10-28 17:29:33 -070093 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
94 if c.config.Bugs.BadRenegotiationInfo {
95 hello.secureRenegotiation = append(hello.secureRenegotiation, c.clientVerify...)
96 hello.secureRenegotiation[0] ^= 0x80
97 } else {
98 hello.secureRenegotiation = c.clientVerify
99 }
100 }
101
David Benjamin3e052de2015-11-25 20:10:31 -0500102 if c.noRenegotiationInfo() {
David Benjaminca6554b2014-11-08 12:31:52 -0500103 hello.secureRenegotiation = nil
104 }
105
Nick Harperb41d2e42016-07-01 17:50:32 -0400106 var keyShares map[CurveID]ecdhCurve
107 if hello.vers >= VersionTLS13 && enableTLS13Handshake {
108 // Offer every supported curve in the initial ClientHello.
109 //
110 // TODO(davidben): For real code, default to a more conservative
111 // set like P-256 and X25519. Make it configurable for tests to
112 // stress the HelloRetryRequest logic when implemented.
113 keyShares = make(map[CurveID]ecdhCurve)
114 for _, curveID := range hello.supportedCurves {
115 curve, ok := curveForCurveID(curveID)
116 if !ok {
117 continue
118 }
119 publicKey, err := curve.offer(c.config.rand())
120 if err != nil {
121 return err
122 }
123 hello.keyShares = append(hello.keyShares, keyShareEntry{
124 group: curveID,
125 keyExchange: publicKey,
126 })
127 keyShares[curveID] = curve
128 }
129 }
130
Adam Langley95c29f32014-06-20 12:00:00 -0700131 possibleCipherSuites := c.config.cipherSuites()
132 hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
133
134NextCipherSuite:
135 for _, suiteId := range possibleCipherSuites {
136 for _, suite := range cipherSuites {
137 if suite.id != suiteId {
138 continue
139 }
David Benjamin0407e762016-06-17 16:41:18 -0400140 if !c.config.Bugs.EnableAllCiphers {
141 // Don't advertise TLS 1.2-only cipher suites unless
142 // we're attempting TLS 1.2.
143 if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
144 continue
145 }
146 // Don't advertise non-DTLS cipher suites in DTLS.
147 if c.isDTLS && suite.flags&suiteNoDTLS != 0 {
148 continue
149 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400150 }
Adam Langley95c29f32014-06-20 12:00:00 -0700151 hello.cipherSuites = append(hello.cipherSuites, suiteId)
152 continue NextCipherSuite
153 }
154 }
155
Adam Langley5021b222015-06-12 18:27:58 -0700156 if c.config.Bugs.SendRenegotiationSCSV {
157 hello.cipherSuites = append(hello.cipherSuites, renegotiationSCSV)
158 }
159
David Benjaminbef270a2014-08-02 04:22:02 -0400160 if c.config.Bugs.SendFallbackSCSV {
161 hello.cipherSuites = append(hello.cipherSuites, fallbackSCSV)
162 }
163
Adam Langley95c29f32014-06-20 12:00:00 -0700164 _, err := io.ReadFull(c.config.rand(), hello.random)
165 if err != nil {
166 c.sendAlert(alertInternalError)
167 return errors.New("tls: short read from Rand: " + err.Error())
168 }
169
Nick Harper60edffd2016-06-21 15:19:24 -0700170 if hello.vers >= VersionTLS12 && !c.config.Bugs.NoSignatureAlgorithms {
171 hello.signatureAlgorithms = c.config.signatureAlgorithmsForClient()
Adam Langley95c29f32014-06-20 12:00:00 -0700172 }
173
174 var session *ClientSessionState
175 var cacheKey string
176 sessionCache := c.config.ClientSessionCache
Adam Langley95c29f32014-06-20 12:00:00 -0700177
178 if sessionCache != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500179 hello.ticketSupported = !c.config.SessionTicketsDisabled
Adam Langley95c29f32014-06-20 12:00:00 -0700180
181 // Try to resume a previously negotiated TLS session, if
182 // available.
183 cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
184 candidateSession, ok := sessionCache.Get(cacheKey)
185 if ok {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500186 ticketOk := !c.config.SessionTicketsDisabled || candidateSession.sessionTicket == nil
187
Adam Langley95c29f32014-06-20 12:00:00 -0700188 // Check that the ciphersuite/version used for the
189 // previous session are still valid.
190 cipherSuiteOk := false
191 for _, id := range hello.cipherSuites {
192 if id == candidateSession.cipherSuite {
193 cipherSuiteOk = true
194 break
195 }
196 }
197
David Benjamincecee272016-06-30 13:33:47 -0400198 versOk := candidateSession.vers >= c.config.minVersion(c.isDTLS) &&
199 candidateSession.vers <= c.config.maxVersion(c.isDTLS)
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500200 if ticketOk && versOk && cipherSuiteOk {
Adam Langley95c29f32014-06-20 12:00:00 -0700201 session = candidateSession
202 }
203 }
204 }
205
206 if session != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500207 if session.sessionTicket != nil {
208 hello.sessionTicket = session.sessionTicket
209 if c.config.Bugs.CorruptTicket {
210 hello.sessionTicket = make([]byte, len(session.sessionTicket))
211 copy(hello.sessionTicket, session.sessionTicket)
212 if len(hello.sessionTicket) > 0 {
213 offset := 40
214 if offset > len(hello.sessionTicket) {
215 offset = len(hello.sessionTicket) - 1
216 }
217 hello.sessionTicket[offset] ^= 0x40
Adam Langley38311732014-10-16 19:04:35 -0700218 }
Adam Langley38311732014-10-16 19:04:35 -0700219 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500220 // A random session ID is used to detect when the
221 // server accepted the ticket and is resuming a session
222 // (see RFC 5077).
223 sessionIdLen := 16
224 if c.config.Bugs.OversizedSessionId {
225 sessionIdLen = 33
226 }
227 hello.sessionId = make([]byte, sessionIdLen)
228 if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
229 c.sendAlert(alertInternalError)
230 return errors.New("tls: short read from Rand: " + err.Error())
231 }
232 } else {
233 hello.sessionId = session.sessionId
Adam Langley95c29f32014-06-20 12:00:00 -0700234 }
235 }
236
David Benjamind86c7672014-08-02 04:07:12 -0400237 var helloBytes []byte
238 if c.config.Bugs.SendV2ClientHello {
David Benjamin94d701b2014-11-30 13:54:41 -0500239 // Test that the peer left-pads random.
240 hello.random[0] = 0
David Benjamind86c7672014-08-02 04:07:12 -0400241 v2Hello := &v2ClientHelloMsg{
242 vers: hello.vers,
243 cipherSuites: hello.cipherSuites,
244 // No session resumption for V2ClientHello.
245 sessionId: nil,
David Benjamin94d701b2014-11-30 13:54:41 -0500246 challenge: hello.random[1:],
David Benjamind86c7672014-08-02 04:07:12 -0400247 }
248 helloBytes = v2Hello.marshal()
249 c.writeV2Record(helloBytes)
250 } else {
251 helloBytes = hello.marshal()
252 c.writeRecord(recordTypeHandshake, helloBytes)
253 }
David Benjamin582ba042016-07-07 12:33:25 -0700254 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700255
David Benjamin83f90402015-01-27 01:09:43 -0500256 if err := c.simulatePacketLoss(nil); err != nil {
257 return err
258 }
Adam Langley95c29f32014-06-20 12:00:00 -0700259 msg, err := c.readHandshake()
260 if err != nil {
261 return err
262 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400263
264 if c.isDTLS {
265 helloVerifyRequest, ok := msg.(*helloVerifyRequestMsg)
266 if ok {
David Benjamin8bc38f52014-08-16 12:07:27 -0400267 if helloVerifyRequest.vers != VersionTLS10 {
268 // Per RFC 6347, the version field in
269 // HelloVerifyRequest SHOULD be always DTLS
270 // 1.0. Enforce this for testing purposes.
271 return errors.New("dtls: bad HelloVerifyRequest version")
272 }
273
David Benjamin83c0bc92014-08-04 01:23:53 -0400274 hello.raw = nil
275 hello.cookie = helloVerifyRequest.cookie
276 helloBytes = hello.marshal()
277 c.writeRecord(recordTypeHandshake, helloBytes)
David Benjamin582ba042016-07-07 12:33:25 -0700278 c.flushHandshake()
David Benjamin83c0bc92014-08-04 01:23:53 -0400279
David Benjamin83f90402015-01-27 01:09:43 -0500280 if err := c.simulatePacketLoss(nil); err != nil {
281 return err
282 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400283 msg, err = c.readHandshake()
284 if err != nil {
285 return err
286 }
287 }
288 }
289
Nick Harperb41d2e42016-07-01 17:50:32 -0400290 // TODO(davidben): Handle HelloRetryRequest.
Adam Langley95c29f32014-06-20 12:00:00 -0700291 serverHello, ok := msg.(*serverHelloMsg)
292 if !ok {
293 c.sendAlert(alertUnexpectedMessage)
294 return unexpectedMessageError(serverHello, msg)
295 }
296
David Benjamincecee272016-06-30 13:33:47 -0400297 c.vers, ok = c.config.mutualVersion(serverHello.vers, c.isDTLS)
David Benjamin76d8abe2014-08-14 16:25:34 -0400298 if !ok {
Adam Langley95c29f32014-06-20 12:00:00 -0700299 c.sendAlert(alertProtocolVersion)
300 return fmt.Errorf("tls: server selected unsupported protocol version %x", serverHello.vers)
301 }
Adam Langley95c29f32014-06-20 12:00:00 -0700302 c.haveVers = true
303
304 suite := mutualCipherSuite(c.config.cipherSuites(), serverHello.cipherSuite)
305 if suite == nil {
306 c.sendAlert(alertHandshakeFailure)
307 return fmt.Errorf("tls: server selected an unsupported cipher suite")
308 }
309
310 hs := &clientHandshakeState{
311 c: c,
312 serverHello: serverHello,
313 hello: hello,
314 suite: suite,
315 finishedHash: newFinishedHash(c.vers, suite),
Nick Harperb41d2e42016-07-01 17:50:32 -0400316 keyShares: keyShares,
Adam Langley95c29f32014-06-20 12:00:00 -0700317 session: session,
318 }
319
David Benjamin83c0bc92014-08-04 01:23:53 -0400320 hs.writeHash(helloBytes, hs.c.sendHandshakeSeq-1)
321 hs.writeServerHash(hs.serverHello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700322
Nick Harperb41d2e42016-07-01 17:50:32 -0400323 if c.vers >= VersionTLS13 && enableTLS13Handshake {
324 if err := hs.doTLS13Handshake(); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700325 return err
326 }
327 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400328 if c.config.Bugs.EarlyChangeCipherSpec > 0 {
329 hs.establishKeys()
330 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
331 }
332
333 if hs.serverHello.compressionMethod != compressionNone {
334 c.sendAlert(alertUnexpectedMessage)
335 return errors.New("tls: server selected unsupported compression format")
336 }
337
338 err = hs.processServerExtensions(&serverHello.extensions)
339 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700340 return err
341 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400342
343 isResume, err := hs.processServerHello()
344 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700345 return err
346 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400347
348 if isResume {
349 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
350 if err := hs.establishKeys(); err != nil {
351 return err
352 }
353 }
354 if err := hs.readSessionTicket(); err != nil {
355 return err
356 }
357 if err := hs.readFinished(c.firstFinished[:]); err != nil {
358 return err
359 }
360 if err := hs.sendFinished(nil, isResume); err != nil {
361 return err
362 }
363 } else {
364 if err := hs.doFullHandshake(); err != nil {
365 return err
366 }
367 if err := hs.establishKeys(); err != nil {
368 return err
369 }
370 if err := hs.sendFinished(c.firstFinished[:], isResume); err != nil {
371 return err
372 }
373 // Most retransmits are triggered by a timeout, but the final
374 // leg of the handshake is retransmited upon re-receiving a
375 // Finished.
376 if err := c.simulatePacketLoss(func() {
377 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
378 c.flushHandshake()
379 }); err != nil {
380 return err
381 }
382 if err := hs.readSessionTicket(); err != nil {
383 return err
384 }
385 if err := hs.readFinished(nil); err != nil {
386 return err
387 }
Adam Langley95c29f32014-06-20 12:00:00 -0700388 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400389
390 if sessionCache != nil && hs.session != nil && session != hs.session {
391 if c.config.Bugs.RequireSessionTickets && len(hs.session.sessionTicket) == 0 {
392 return errors.New("tls: new session used session IDs instead of tickets")
393 }
394 sessionCache.Put(cacheKey, hs.session)
David Benjamin83f90402015-01-27 01:09:43 -0500395 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400396
397 c.didResume = isResume
Adam Langley95c29f32014-06-20 12:00:00 -0700398 }
399
Adam Langley95c29f32014-06-20 12:00:00 -0700400 c.handshakeComplete = true
David Benjaminc565ebb2015-04-03 04:06:36 -0400401 c.cipherSuite = suite
402 copy(c.clientRandom[:], hs.hello.random)
403 copy(c.serverRandom[:], hs.serverHello.random)
404 copy(c.masterSecret[:], hs.masterSecret)
Paul Lietar4fac72e2015-09-09 13:44:55 +0100405
Adam Langley95c29f32014-06-20 12:00:00 -0700406 return nil
407}
408
Nick Harperb41d2e42016-07-01 17:50:32 -0400409func (hs *clientHandshakeState) doTLS13Handshake() error {
410 c := hs.c
411
412 // Once the PRF hash is known, TLS 1.3 does not require a handshake
413 // buffer.
414 hs.finishedHash.discardHandshakeBuffer()
415
416 zeroSecret := hs.finishedHash.zeroSecret()
417
418 // Resolve PSK and compute the early secret.
419 //
420 // TODO(davidben): This will need to be handled slightly earlier once
421 // 0-RTT is implemented.
422 var psk []byte
423 if hs.suite.flags&suitePSK != 0 {
424 if !hs.serverHello.hasPSKIdentity {
425 c.sendAlert(alertMissingExtension)
426 return errors.New("tls: server omitted the PSK identity extension")
427 }
428
429 // TODO(davidben): Support PSK ciphers and PSK resumption. Set
430 // the resumption context appropriately if resuming.
431 return errors.New("tls: PSK ciphers not implemented for TLS 1.3")
432 } else {
433 if hs.serverHello.hasPSKIdentity {
434 c.sendAlert(alertUnsupportedExtension)
435 return errors.New("tls: server sent unexpected PSK identity")
436 }
437
438 psk = zeroSecret
439 hs.finishedHash.setResumptionContext(zeroSecret)
440 }
441
442 earlySecret := hs.finishedHash.extractKey(zeroSecret, psk)
443
444 // Resolve ECDHE and compute the handshake secret.
445 var ecdheSecret []byte
446 if hs.suite.flags&suiteECDHE != 0 {
447 if !hs.serverHello.hasKeyShare {
448 c.sendAlert(alertMissingExtension)
449 return errors.New("tls: server omitted the key share extension")
450 }
451
452 curve, ok := hs.keyShares[hs.serverHello.keyShare.group]
453 if !ok {
454 c.sendAlert(alertHandshakeFailure)
455 return errors.New("tls: server selected an unsupported group")
456 }
457
458 var err error
459 ecdheSecret, err = curve.finish(hs.serverHello.keyShare.keyExchange)
460 if err != nil {
461 return err
462 }
463 } else {
464 if hs.serverHello.hasKeyShare {
465 c.sendAlert(alertUnsupportedExtension)
466 return errors.New("tls: server sent unexpected key share extension")
467 }
468
469 ecdheSecret = zeroSecret
470 }
471
472 // Compute the handshake secret.
473 handshakeSecret := hs.finishedHash.extractKey(earlySecret, ecdheSecret)
474
475 // Switch to handshake traffic keys.
476 handshakeTrafficSecret := hs.finishedHash.deriveSecret(handshakeSecret, handshakeTrafficLabel)
477 c.out.updateKeys(deriveTrafficAEAD(c.vers, hs.suite, handshakeTrafficSecret, handshakePhase, clientWrite), c.vers)
478 c.in.updateKeys(deriveTrafficAEAD(c.vers, hs.suite, handshakeTrafficSecret, handshakePhase, serverWrite), c.vers)
479
480 msg, err := c.readHandshake()
481 if err != nil {
482 return err
483 }
484
485 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
486 if !ok {
487 c.sendAlert(alertUnexpectedMessage)
488 return unexpectedMessageError(encryptedExtensions, msg)
489 }
490 hs.writeServerHash(encryptedExtensions.marshal())
491
492 err = hs.processServerExtensions(&encryptedExtensions.extensions)
493 if err != nil {
494 return err
495 }
496
497 var chainToSend *Certificate
498 var certRequested bool
499 var certRequestContext []byte
500 if hs.suite.flags&suitePSK == 0 {
501 // TODO(davidben): Save OCSP response and SCT list. Forbid them
502 // if not negotiating a certificate-based extension.
503
504 msg, err := c.readHandshake()
505 if err != nil {
506 return err
507 }
508
509 certReq, ok := msg.(*certificateRequestMsg)
510 if ok {
511 hs.writeServerHash(certReq.marshal())
512 certRequested = true
513 certRequestContext = certReq.requestContext
514
515 chainToSend, err = selectClientCertificate(c, certReq)
516 if err != nil {
517 return err
518 }
519
520 msg, err = c.readHandshake()
521 if err != nil {
522 return err
523 }
524 }
525
526 certMsg, ok := msg.(*certificateMsg)
527 if !ok {
528 c.sendAlert(alertUnexpectedMessage)
529 return unexpectedMessageError(certMsg, msg)
530 }
531 hs.writeServerHash(certMsg.marshal())
532
533 if err := hs.verifyCertificates(certMsg); err != nil {
534 return err
535 }
536 leaf := c.peerCertificates[0]
537
538 msg, err = c.readHandshake()
539 if err != nil {
540 return err
541 }
542 certVerifyMsg, ok := msg.(*certificateVerifyMsg)
543 if !ok {
544 c.sendAlert(alertUnexpectedMessage)
545 return unexpectedMessageError(certVerifyMsg, msg)
546 }
547
548 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
549 err = verifyMessage(c.vers, leaf.PublicKey, certVerifyMsg.signatureAlgorithm, input, certVerifyMsg.signature)
550 if err != nil {
551 return err
552 }
553
554 hs.writeServerHash(certVerifyMsg.marshal())
555 }
556
557 msg, err = c.readHandshake()
558 if err != nil {
559 return err
560 }
561 serverFinished, ok := msg.(*finishedMsg)
562 if !ok {
563 c.sendAlert(alertUnexpectedMessage)
564 return unexpectedMessageError(serverFinished, msg)
565 }
566
567 verify := hs.finishedHash.serverSum(handshakeTrafficSecret)
568 if len(verify) != len(serverFinished.verifyData) ||
569 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
570 c.sendAlert(alertHandshakeFailure)
571 return errors.New("tls: server's Finished message was incorrect")
572 }
573
574 hs.writeServerHash(serverFinished.marshal())
575
576 // The various secrets do not incorporate the client's final leg, so
577 // derive them now before updating the handshake context.
578 masterSecret := hs.finishedHash.extractKey(handshakeSecret, zeroSecret)
579 trafficSecret := hs.finishedHash.deriveSecret(masterSecret, applicationTrafficLabel)
580
581 if certRequested {
582 _ = chainToSend
583 _ = certRequestContext
584 return errors.New("tls: client auth not implemented.")
585 }
586
587 // Send a client Finished message.
588 finished := new(finishedMsg)
589 finished.verifyData = hs.finishedHash.clientSum(handshakeTrafficSecret)
590 if c.config.Bugs.BadFinished {
591 finished.verifyData[0]++
592 }
593 c.writeRecord(recordTypeHandshake, finished.marshal())
594
595 // Switch to application data keys.
596 c.out.updateKeys(deriveTrafficAEAD(c.vers, hs.suite, trafficSecret, applicationPhase, clientWrite), c.vers)
597 c.in.updateKeys(deriveTrafficAEAD(c.vers, hs.suite, trafficSecret, applicationPhase, serverWrite), c.vers)
598
599 // TODO(davidben): Derive and save the exporter master secret for key exporters. Swap out the masterSecret field.
600 // TODO(davidben): Derive and save the resumption master secret for receiving tickets.
601 // TODO(davidben): Save the traffic secret for KeyUpdate.
602 return nil
603}
604
Adam Langley95c29f32014-06-20 12:00:00 -0700605func (hs *clientHandshakeState) doFullHandshake() error {
606 c := hs.c
607
David Benjamin48cae082014-10-27 01:06:24 -0400608 var leaf *x509.Certificate
609 if hs.suite.flags&suitePSK == 0 {
610 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700611 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700612 return err
613 }
Adam Langley95c29f32014-06-20 12:00:00 -0700614
David Benjamin48cae082014-10-27 01:06:24 -0400615 certMsg, ok := msg.(*certificateMsg)
David Benjamin75051442016-07-01 18:58:51 -0400616 if !ok {
David Benjamin48cae082014-10-27 01:06:24 -0400617 c.sendAlert(alertUnexpectedMessage)
618 return unexpectedMessageError(certMsg, msg)
619 }
620 hs.writeServerHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700621
David Benjamin75051442016-07-01 18:58:51 -0400622 if err := hs.verifyCertificates(certMsg); err != nil {
623 return err
David Benjamin48cae082014-10-27 01:06:24 -0400624 }
David Benjamin75051442016-07-01 18:58:51 -0400625 leaf = c.peerCertificates[0]
David Benjamin48cae082014-10-27 01:06:24 -0400626 }
Adam Langley95c29f32014-06-20 12:00:00 -0700627
Nick Harperb3d51be2016-07-01 11:43:18 -0400628 if hs.serverHello.extensions.ocspStapling {
David Benjamin48cae082014-10-27 01:06:24 -0400629 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700630 if err != nil {
631 return err
632 }
633 cs, ok := msg.(*certificateStatusMsg)
634 if !ok {
635 c.sendAlert(alertUnexpectedMessage)
636 return unexpectedMessageError(cs, msg)
637 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400638 hs.writeServerHash(cs.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700639
640 if cs.statusType == statusTypeOCSP {
641 c.ocspResponse = cs.response
642 }
643 }
644
David Benjamin48cae082014-10-27 01:06:24 -0400645 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700646 if err != nil {
647 return err
648 }
649
650 keyAgreement := hs.suite.ka(c.vers)
651
652 skx, ok := msg.(*serverKeyExchangeMsg)
653 if ok {
David Benjamin83c0bc92014-08-04 01:23:53 -0400654 hs.writeServerHash(skx.marshal())
David Benjamin48cae082014-10-27 01:06:24 -0400655 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, leaf, skx)
Adam Langley95c29f32014-06-20 12:00:00 -0700656 if err != nil {
657 c.sendAlert(alertUnexpectedMessage)
658 return err
659 }
660
Nick Harper60edffd2016-06-21 15:19:24 -0700661 c.peerSignatureAlgorithm = keyAgreement.peerSignatureAlgorithm()
662
Adam Langley95c29f32014-06-20 12:00:00 -0700663 msg, err = c.readHandshake()
664 if err != nil {
665 return err
666 }
667 }
668
669 var chainToSend *Certificate
670 var certRequested bool
671 certReq, ok := msg.(*certificateRequestMsg)
672 if ok {
673 certRequested = true
674
David Benjamin83c0bc92014-08-04 01:23:53 -0400675 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700676
David Benjamina6f82632016-07-01 18:44:02 -0400677 chainToSend, err = selectClientCertificate(c, certReq)
678 if err != nil {
679 return err
Adam Langley95c29f32014-06-20 12:00:00 -0700680 }
681
682 msg, err = c.readHandshake()
683 if err != nil {
684 return err
685 }
686 }
687
688 shd, ok := msg.(*serverHelloDoneMsg)
689 if !ok {
690 c.sendAlert(alertUnexpectedMessage)
691 return unexpectedMessageError(shd, msg)
692 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400693 hs.writeServerHash(shd.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700694
695 // If the server requested a certificate then we have to send a
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500696 // Certificate message in TLS, even if it's empty because we don't have
697 // a certificate to send. In SSL 3.0, skip the message and send a
698 // no_certificate warning alert.
Adam Langley95c29f32014-06-20 12:00:00 -0700699 if certRequested {
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500700 if c.vers == VersionSSL30 && chainToSend == nil {
701 c.sendAlert(alertNoCertficate)
702 } else if !c.config.Bugs.SkipClientCertificate {
703 certMsg := new(certificateMsg)
704 if chainToSend != nil {
705 certMsg.certificates = chainToSend.Certificate
706 }
707 hs.writeClientHash(certMsg.marshal())
708 c.writeRecord(recordTypeHandshake, certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700709 }
Adam Langley95c29f32014-06-20 12:00:00 -0700710 }
711
David Benjamin48cae082014-10-27 01:06:24 -0400712 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, leaf)
Adam Langley95c29f32014-06-20 12:00:00 -0700713 if err != nil {
714 c.sendAlert(alertInternalError)
715 return err
716 }
717 if ckx != nil {
David Benjaminf3ec83d2014-07-21 22:42:34 -0400718 if c.config.Bugs.EarlyChangeCipherSpec < 2 {
David Benjamin83c0bc92014-08-04 01:23:53 -0400719 hs.writeClientHash(ckx.marshal())
David Benjaminf3ec83d2014-07-21 22:42:34 -0400720 }
Adam Langley95c29f32014-06-20 12:00:00 -0700721 c.writeRecord(recordTypeHandshake, ckx.marshal())
722 }
723
Nick Harperb3d51be2016-07-01 11:43:18 -0400724 if hs.serverHello.extensions.extendedMasterSecret && c.vers >= VersionTLS10 {
Adam Langley75712922014-10-10 16:23:43 -0700725 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
726 c.extendedMasterSecret = true
727 } else {
728 if c.config.Bugs.RequireExtendedMasterSecret {
729 return errors.New("tls: extended master secret required but not supported by peer")
730 }
731 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
732 }
David Benjamine098ec22014-08-27 23:13:20 -0400733
Adam Langley95c29f32014-06-20 12:00:00 -0700734 if chainToSend != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700735 certVerify := &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -0700736 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -0700737 }
738
David Benjamin72dc7832015-03-16 17:49:43 -0400739 // Determine the hash to sign.
Nick Harper60edffd2016-06-21 15:19:24 -0700740 privKey := c.config.Certificates[0].PrivateKey
David Benjamin72dc7832015-03-16 17:49:43 -0400741 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
Nick Harper60edffd2016-06-21 15:19:24 -0700742 certReq.signatureAlgorithms = c.config.signatureAlgorithmsForClient()
David Benjamin6de0e532015-07-28 22:43:19 -0400743 }
David Benjamin72dc7832015-03-16 17:49:43 -0400744
Nick Harper60edffd2016-06-21 15:19:24 -0700745 if certVerify.hasSignatureAlgorithm {
746 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, certReq.signatureAlgorithms, c.config.signatureAlgorithmsForClient())
747 if err != nil {
748 c.sendAlert(alertInternalError)
749 return err
Adam Langley95c29f32014-06-20 12:00:00 -0700750 }
Nick Harper60edffd2016-06-21 15:19:24 -0700751 }
752
753 if c.vers > VersionSSL30 {
754 msg := hs.finishedHash.buffer
755 if c.config.Bugs.InvalidCertVerifySignature {
756 msg = make([]byte, len(hs.finishedHash.buffer))
757 copy(msg, hs.finishedHash.buffer)
758 msg[0] ^= 0x80
759 }
760 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, msg)
761 } else {
762 // SSL 3.0's client certificate construction is
763 // incompatible with signatureAlgorithm.
764 rsaKey, ok := privKey.(*rsa.PrivateKey)
765 if !ok {
766 err = errors.New("unsupported signature type for client certificate")
767 } else {
768 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
769 if c.config.Bugs.InvalidCertVerifySignature {
770 digest[0] ^= 0x80
771 }
772 certVerify.signature, err = rsa.SignPKCS1v15(c.config.rand(), rsaKey, crypto.MD5SHA1, digest)
773 }
Adam Langley95c29f32014-06-20 12:00:00 -0700774 }
775 if err != nil {
776 c.sendAlert(alertInternalError)
777 return errors.New("tls: failed to sign handshake with client certificate: " + err.Error())
778 }
Adam Langley95c29f32014-06-20 12:00:00 -0700779
David Benjamin83c0bc92014-08-04 01:23:53 -0400780 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700781 c.writeRecord(recordTypeHandshake, certVerify.marshal())
782 }
David Benjamin582ba042016-07-07 12:33:25 -0700783 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700784
David Benjamine098ec22014-08-27 23:13:20 -0400785 hs.finishedHash.discardHandshakeBuffer()
786
Adam Langley95c29f32014-06-20 12:00:00 -0700787 return nil
788}
789
David Benjamin75051442016-07-01 18:58:51 -0400790func (hs *clientHandshakeState) verifyCertificates(certMsg *certificateMsg) error {
791 c := hs.c
792
793 if len(certMsg.certificates) == 0 {
794 c.sendAlert(alertIllegalParameter)
795 return errors.New("tls: no certificates sent")
796 }
797
798 certs := make([]*x509.Certificate, len(certMsg.certificates))
799 for i, asn1Data := range certMsg.certificates {
800 cert, err := x509.ParseCertificate(asn1Data)
801 if err != nil {
802 c.sendAlert(alertBadCertificate)
803 return errors.New("tls: failed to parse certificate from server: " + err.Error())
804 }
805 certs[i] = cert
806 }
807
808 if !c.config.InsecureSkipVerify {
809 opts := x509.VerifyOptions{
810 Roots: c.config.RootCAs,
811 CurrentTime: c.config.time(),
812 DNSName: c.config.ServerName,
813 Intermediates: x509.NewCertPool(),
814 }
815
816 for i, cert := range certs {
817 if i == 0 {
818 continue
819 }
820 opts.Intermediates.AddCert(cert)
821 }
822 var err error
823 c.verifiedChains, err = certs[0].Verify(opts)
824 if err != nil {
825 c.sendAlert(alertBadCertificate)
826 return err
827 }
828 }
829
830 switch certs[0].PublicKey.(type) {
831 case *rsa.PublicKey, *ecdsa.PublicKey:
832 break
833 default:
834 c.sendAlert(alertUnsupportedCertificate)
835 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
836 }
837
838 c.peerCertificates = certs
839 return nil
840}
841
Adam Langley95c29f32014-06-20 12:00:00 -0700842func (hs *clientHandshakeState) establishKeys() error {
843 c := hs.c
844
845 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -0700846 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen(c.vers))
Adam Langley95c29f32014-06-20 12:00:00 -0700847 var clientCipher, serverCipher interface{}
848 var clientHash, serverHash macFunction
849 if hs.suite.cipher != nil {
850 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
851 clientHash = hs.suite.mac(c.vers, clientMAC)
852 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
853 serverHash = hs.suite.mac(c.vers, serverMAC)
854 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -0700855 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
856 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -0700857 }
858
859 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
860 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
861 return nil
862}
863
David Benjamin75101402016-07-01 13:40:23 -0400864func (hs *clientHandshakeState) processServerExtensions(serverExtensions *serverExtensions) error {
865 c := hs.c
866
Nick Harperb41d2e42016-07-01 17:50:32 -0400867 if c.vers < VersionTLS13 || !enableTLS13Handshake {
868 if c.config.Bugs.RequireRenegotiationInfo && serverExtensions.secureRenegotiation == nil {
869 return errors.New("tls: renegotiation extension missing")
870 }
David Benjamin75101402016-07-01 13:40:23 -0400871
Nick Harperb41d2e42016-07-01 17:50:32 -0400872 if len(c.clientVerify) > 0 && !c.noRenegotiationInfo() {
873 var expectedRenegInfo []byte
874 expectedRenegInfo = append(expectedRenegInfo, c.clientVerify...)
875 expectedRenegInfo = append(expectedRenegInfo, c.serverVerify...)
876 if !bytes.Equal(serverExtensions.secureRenegotiation, expectedRenegInfo) {
877 c.sendAlert(alertHandshakeFailure)
878 return fmt.Errorf("tls: renegotiation mismatch")
879 }
David Benjamin75101402016-07-01 13:40:23 -0400880 }
881 }
882
883 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
884 if serverExtensions.customExtension != *expected {
885 return fmt.Errorf("tls: bad custom extension contents %q", serverExtensions.customExtension)
886 }
887 }
888
889 clientDidNPN := hs.hello.nextProtoNeg
890 clientDidALPN := len(hs.hello.alpnProtocols) > 0
891 serverHasNPN := serverExtensions.nextProtoNeg
892 serverHasALPN := len(serverExtensions.alpnProtocol) > 0
893
894 if !clientDidNPN && serverHasNPN {
895 c.sendAlert(alertHandshakeFailure)
896 return errors.New("server advertised unrequested NPN extension")
897 }
898
899 if !clientDidALPN && serverHasALPN {
900 c.sendAlert(alertHandshakeFailure)
901 return errors.New("server advertised unrequested ALPN extension")
902 }
903
904 if serverHasNPN && serverHasALPN {
905 c.sendAlert(alertHandshakeFailure)
906 return errors.New("server advertised both NPN and ALPN extensions")
907 }
908
909 if serverHasALPN {
910 c.clientProtocol = serverExtensions.alpnProtocol
911 c.clientProtocolFallback = false
912 c.usedALPN = true
913 }
914
Nick Harperb41d2e42016-07-01 17:50:32 -0400915 if serverHasNPN && c.vers >= VersionTLS13 && enableTLS13Handshake {
916 c.sendAlert(alertHandshakeFailure)
917 return errors.New("server advertised NPN over TLS 1.3")
918 }
919
David Benjamin75101402016-07-01 13:40:23 -0400920 if !hs.hello.channelIDSupported && serverExtensions.channelIDRequested {
921 c.sendAlert(alertHandshakeFailure)
922 return errors.New("server advertised unrequested Channel ID extension")
923 }
924
Nick Harperb41d2e42016-07-01 17:50:32 -0400925 if serverExtensions.channelIDRequested && c.vers >= VersionTLS13 && enableTLS13Handshake {
926 c.sendAlert(alertHandshakeFailure)
927 return errors.New("server advertised Channel ID over TLS 1.3")
928 }
929
David Benjamin75101402016-07-01 13:40:23 -0400930 if serverExtensions.srtpProtectionProfile != 0 {
931 if serverExtensions.srtpMasterKeyIdentifier != "" {
932 return errors.New("tls: server selected SRTP MKI value")
933 }
934
935 found := false
936 for _, p := range c.config.SRTPProtectionProfiles {
937 if p == serverExtensions.srtpProtectionProfile {
938 found = true
939 break
940 }
941 }
942 if !found {
943 return errors.New("tls: server advertised unsupported SRTP profile")
944 }
945
946 c.srtpProtectionProfile = serverExtensions.srtpProtectionProfile
947 }
948
949 return nil
950}
951
Adam Langley95c29f32014-06-20 12:00:00 -0700952func (hs *clientHandshakeState) serverResumedSession() bool {
953 // If the server responded with the same sessionId then it means the
954 // sessionTicket is being used to resume a TLS session.
955 return hs.session != nil && hs.hello.sessionId != nil &&
956 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
957}
958
959func (hs *clientHandshakeState) processServerHello() (bool, error) {
960 c := hs.c
961
Adam Langley95c29f32014-06-20 12:00:00 -0700962 if hs.serverResumedSession() {
David Benjamin4b27d9f2015-05-12 22:42:52 -0400963 // For test purposes, assert that the server never accepts the
964 // resumption offer on renegotiation.
965 if c.cipherSuite != nil && c.config.Bugs.FailIfResumeOnRenego {
966 return false, errors.New("tls: server resumed session on renegotiation")
967 }
968
Nick Harperb3d51be2016-07-01 11:43:18 -0400969 if hs.serverHello.extensions.sctList != nil {
Paul Lietar62be8ac2015-09-16 10:03:30 +0100970 return false, errors.New("tls: server sent SCT extension on session resumption")
971 }
972
Nick Harperb3d51be2016-07-01 11:43:18 -0400973 if hs.serverHello.extensions.ocspStapling {
Paul Lietar62be8ac2015-09-16 10:03:30 +0100974 return false, errors.New("tls: server sent OCSP extension on session resumption")
975 }
976
Adam Langley95c29f32014-06-20 12:00:00 -0700977 // Restore masterSecret and peerCerts from previous state
978 hs.masterSecret = hs.session.masterSecret
979 c.peerCertificates = hs.session.serverCertificates
Adam Langley75712922014-10-10 16:23:43 -0700980 c.extendedMasterSecret = hs.session.extendedMasterSecret
Paul Lietar62be8ac2015-09-16 10:03:30 +0100981 c.sctList = hs.session.sctList
982 c.ocspResponse = hs.session.ocspResponse
David Benjamine098ec22014-08-27 23:13:20 -0400983 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -0700984 return true, nil
985 }
Paul Lietar62be8ac2015-09-16 10:03:30 +0100986
Nick Harperb3d51be2016-07-01 11:43:18 -0400987 if hs.serverHello.extensions.sctList != nil {
988 c.sctList = hs.serverHello.extensions.sctList
Paul Lietar62be8ac2015-09-16 10:03:30 +0100989 }
990
Adam Langley95c29f32014-06-20 12:00:00 -0700991 return false, nil
992}
993
Adam Langleyaf0e32c2015-06-03 09:57:23 -0700994func (hs *clientHandshakeState) readFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700995 c := hs.c
996
997 c.readRecord(recordTypeChangeCipherSpec)
998 if err := c.in.error(); err != nil {
999 return err
1000 }
1001
1002 msg, err := c.readHandshake()
1003 if err != nil {
1004 return err
1005 }
1006 serverFinished, ok := msg.(*finishedMsg)
1007 if !ok {
1008 c.sendAlert(alertUnexpectedMessage)
1009 return unexpectedMessageError(serverFinished, msg)
1010 }
1011
David Benjaminf3ec83d2014-07-21 22:42:34 -04001012 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
1013 verify := hs.finishedHash.serverSum(hs.masterSecret)
1014 if len(verify) != len(serverFinished.verifyData) ||
1015 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
1016 c.sendAlert(alertHandshakeFailure)
1017 return errors.New("tls: server's Finished message was incorrect")
1018 }
Adam Langley95c29f32014-06-20 12:00:00 -07001019 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001020 c.serverVerify = append(c.serverVerify[:0], serverFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001021 copy(out, serverFinished.verifyData)
David Benjamin83c0bc92014-08-04 01:23:53 -04001022 hs.writeServerHash(serverFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001023 return nil
1024}
1025
1026func (hs *clientHandshakeState) readSessionTicket() error {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001027 c := hs.c
1028
1029 // Create a session with no server identifier. Either a
1030 // session ID or session ticket will be attached.
1031 session := &ClientSessionState{
1032 vers: c.vers,
1033 cipherSuite: hs.suite.id,
1034 masterSecret: hs.masterSecret,
1035 handshakeHash: hs.finishedHash.server.Sum(nil),
1036 serverCertificates: c.peerCertificates,
Paul Lietar62be8ac2015-09-16 10:03:30 +01001037 sctList: c.sctList,
1038 ocspResponse: c.ocspResponse,
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001039 }
1040
Nick Harperb3d51be2016-07-01 11:43:18 -04001041 if !hs.serverHello.extensions.ticketSupported {
David Benjamind98452d2015-06-16 14:16:23 -04001042 if c.config.Bugs.ExpectNewTicket {
1043 return errors.New("tls: expected new ticket")
1044 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001045 if hs.session == nil && len(hs.serverHello.sessionId) > 0 {
1046 session.sessionId = hs.serverHello.sessionId
1047 hs.session = session
1048 }
Adam Langley95c29f32014-06-20 12:00:00 -07001049 return nil
1050 }
1051
David Benjaminc7ce9772015-10-09 19:32:41 -04001052 if c.vers == VersionSSL30 {
1053 return errors.New("tls: negotiated session tickets in SSL 3.0")
1054 }
1055
Adam Langley95c29f32014-06-20 12:00:00 -07001056 msg, err := c.readHandshake()
1057 if err != nil {
1058 return err
1059 }
1060 sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
1061 if !ok {
1062 c.sendAlert(alertUnexpectedMessage)
1063 return unexpectedMessageError(sessionTicketMsg, msg)
1064 }
Adam Langley95c29f32014-06-20 12:00:00 -07001065
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001066 session.sessionTicket = sessionTicketMsg.ticket
1067 hs.session = session
Adam Langley95c29f32014-06-20 12:00:00 -07001068
David Benjamind30a9902014-08-24 01:44:23 -04001069 hs.writeServerHash(sessionTicketMsg.marshal())
1070
Adam Langley95c29f32014-06-20 12:00:00 -07001071 return nil
1072}
1073
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001074func (hs *clientHandshakeState) sendFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001075 c := hs.c
1076
David Benjamin86271ee2014-07-21 16:14:03 -04001077 var postCCSBytes []byte
David Benjamin83c0bc92014-08-04 01:23:53 -04001078 seqno := hs.c.sendHandshakeSeq
Nick Harperb3d51be2016-07-01 11:43:18 -04001079 if hs.serverHello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001080 nextProto := new(nextProtoMsg)
Nick Harperb3d51be2016-07-01 11:43:18 -04001081 proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.extensions.nextProtos)
Adam Langley95c29f32014-06-20 12:00:00 -07001082 nextProto.proto = proto
1083 c.clientProtocol = proto
1084 c.clientProtocolFallback = fallback
1085
David Benjamin86271ee2014-07-21 16:14:03 -04001086 nextProtoBytes := nextProto.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -04001087 hs.writeHash(nextProtoBytes, seqno)
1088 seqno++
David Benjamin86271ee2014-07-21 16:14:03 -04001089 postCCSBytes = append(postCCSBytes, nextProtoBytes...)
Adam Langley95c29f32014-06-20 12:00:00 -07001090 }
1091
Nick Harperb3d51be2016-07-01 11:43:18 -04001092 if hs.serverHello.extensions.channelIDRequested {
David Benjamin24599a82016-06-30 18:56:53 -04001093 channelIDMsg := new(channelIDMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001094 if c.config.ChannelID.Curve != elliptic.P256() {
1095 return fmt.Errorf("tls: Channel ID is not on P-256.")
1096 }
1097 var resumeHash []byte
1098 if isResume {
1099 resumeHash = hs.session.handshakeHash
1100 }
1101 r, s, err := ecdsa.Sign(c.config.rand(), c.config.ChannelID, hs.finishedHash.hashForChannelID(resumeHash))
1102 if err != nil {
1103 return err
1104 }
1105 channelID := make([]byte, 128)
1106 writeIntPadded(channelID[0:32], c.config.ChannelID.X)
1107 writeIntPadded(channelID[32:64], c.config.ChannelID.Y)
1108 writeIntPadded(channelID[64:96], r)
1109 writeIntPadded(channelID[96:128], s)
David Benjamin24599a82016-06-30 18:56:53 -04001110 channelIDMsg.channelID = channelID
David Benjamind30a9902014-08-24 01:44:23 -04001111
1112 c.channelID = &c.config.ChannelID.PublicKey
1113
David Benjamin24599a82016-06-30 18:56:53 -04001114 channelIDMsgBytes := channelIDMsg.marshal()
1115 hs.writeHash(channelIDMsgBytes, seqno)
David Benjamind30a9902014-08-24 01:44:23 -04001116 seqno++
David Benjamin24599a82016-06-30 18:56:53 -04001117 postCCSBytes = append(postCCSBytes, channelIDMsgBytes...)
David Benjamind30a9902014-08-24 01:44:23 -04001118 }
1119
Adam Langley95c29f32014-06-20 12:00:00 -07001120 finished := new(finishedMsg)
David Benjaminf3ec83d2014-07-21 22:42:34 -04001121 if c.config.Bugs.EarlyChangeCipherSpec == 2 {
1122 finished.verifyData = hs.finishedHash.clientSum(nil)
1123 } else {
1124 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
1125 }
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001126 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001127 if c.config.Bugs.BadFinished {
1128 finished.verifyData[0]++
1129 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001130 c.clientVerify = append(c.clientVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001131 hs.finishedBytes = finished.marshal()
1132 hs.writeHash(hs.finishedBytes, seqno)
1133 postCCSBytes = append(postCCSBytes, hs.finishedBytes...)
David Benjamin86271ee2014-07-21 16:14:03 -04001134
1135 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
1136 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
1137 postCCSBytes = postCCSBytes[5:]
1138 }
David Benjamin582ba042016-07-07 12:33:25 -07001139 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001140
1141 if !c.config.Bugs.SkipChangeCipherSpec &&
1142 c.config.Bugs.EarlyChangeCipherSpec == 0 {
David Benjamin8411b242015-11-26 12:07:28 -05001143 ccs := []byte{1}
1144 if c.config.Bugs.BadChangeCipherSpec != nil {
1145 ccs = c.config.Bugs.BadChangeCipherSpec
1146 }
1147 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamin86271ee2014-07-21 16:14:03 -04001148 }
1149
David Benjamin4189bd92015-01-25 23:52:39 -05001150 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1151 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1152 }
David Benjamindc3da932015-03-12 15:09:02 -04001153 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1154 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1155 return errors.New("tls: simulating post-CCS alert")
1156 }
David Benjamin4189bd92015-01-25 23:52:39 -05001157
David Benjaminb80168e2015-02-08 18:30:14 -05001158 if !c.config.Bugs.SkipFinished {
1159 c.writeRecord(recordTypeHandshake, postCCSBytes)
David Benjamin582ba042016-07-07 12:33:25 -07001160 c.flushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -05001161 }
Adam Langley95c29f32014-06-20 12:00:00 -07001162 return nil
1163}
1164
David Benjamin83c0bc92014-08-04 01:23:53 -04001165func (hs *clientHandshakeState) writeClientHash(msg []byte) {
1166 // writeClientHash is called before writeRecord.
1167 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1168}
1169
1170func (hs *clientHandshakeState) writeServerHash(msg []byte) {
1171 // writeServerHash is called after readHandshake.
1172 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1173}
1174
1175func (hs *clientHandshakeState) writeHash(msg []byte, seqno uint16) {
1176 if hs.c.isDTLS {
1177 // This is somewhat hacky. DTLS hashes a slightly different format.
1178 // First, the TLS header.
1179 hs.finishedHash.Write(msg[:4])
1180 // Then the sequence number and reassembled fragment offset (always 0).
1181 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1182 // Then the reassembled fragment (always equal to the message length).
1183 hs.finishedHash.Write(msg[1:4])
1184 // And then the message body.
1185 hs.finishedHash.Write(msg[4:])
1186 } else {
1187 hs.finishedHash.Write(msg)
1188 }
1189}
1190
David Benjamina6f82632016-07-01 18:44:02 -04001191// selectClientCertificate selects a certificate for use with the given
1192// certificate, or none if none match. It may return a particular certificate or
1193// nil on success, or an error on internal error.
1194func selectClientCertificate(c *Conn, certReq *certificateRequestMsg) (*Certificate, error) {
1195 // RFC 4346 on the certificateAuthorities field:
1196 // A list of the distinguished names of acceptable certificate
1197 // authorities. These distinguished names may specify a desired
1198 // distinguished name for a root CA or for a subordinate CA; thus, this
1199 // message can be used to describe both known roots and a desired
1200 // authorization space. If the certificate_authorities list is empty
1201 // then the client MAY send any certificate of the appropriate
1202 // ClientCertificateType, unless there is some external arrangement to
1203 // the contrary.
1204
1205 var rsaAvail, ecdsaAvail bool
Nick Harperb41d2e42016-07-01 17:50:32 -04001206 if !certReq.hasRequestContext {
1207 for _, certType := range certReq.certificateTypes {
1208 switch certType {
1209 case CertTypeRSASign:
1210 rsaAvail = true
1211 case CertTypeECDSASign:
1212 ecdsaAvail = true
1213 }
David Benjamina6f82632016-07-01 18:44:02 -04001214 }
1215 }
1216
1217 // We need to search our list of client certs for one
1218 // where SignatureAlgorithm is RSA and the Issuer is in
1219 // certReq.certificateAuthorities
1220findCert:
1221 for i, chain := range c.config.Certificates {
Nick Harperb41d2e42016-07-01 17:50:32 -04001222 if !certReq.hasRequestContext && !rsaAvail && !ecdsaAvail {
David Benjamina6f82632016-07-01 18:44:02 -04001223 continue
1224 }
1225
1226 // Ensure the private key supports one of the advertised
1227 // signature algorithms.
1228 if certReq.hasSignatureAlgorithm {
1229 if _, err := selectSignatureAlgorithm(c.vers, chain.PrivateKey, certReq.signatureAlgorithms, c.config.signatureAlgorithmsForClient()); err != nil {
1230 continue
1231 }
1232 }
1233
1234 for j, cert := range chain.Certificate {
1235 x509Cert := chain.Leaf
1236 // parse the certificate if this isn't the leaf
1237 // node, or if chain.Leaf was nil
1238 if j != 0 || x509Cert == nil {
1239 var err error
1240 if x509Cert, err = x509.ParseCertificate(cert); err != nil {
1241 c.sendAlert(alertInternalError)
1242 return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
1243 }
1244 }
1245
Nick Harperb41d2e42016-07-01 17:50:32 -04001246 if !certReq.hasRequestContext {
1247 switch {
1248 case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
1249 case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
1250 default:
1251 continue findCert
1252 }
David Benjamina6f82632016-07-01 18:44:02 -04001253 }
1254
1255 if len(certReq.certificateAuthorities) == 0 {
1256 // They gave us an empty list, so just take the
1257 // first certificate of valid type from
1258 // c.config.Certificates.
1259 return &chain, nil
1260 }
1261
1262 for _, ca := range certReq.certificateAuthorities {
1263 if bytes.Equal(x509Cert.RawIssuer, ca) {
1264 return &chain, nil
1265 }
1266 }
1267 }
1268 }
1269
1270 return nil, nil
1271}
1272
Adam Langley95c29f32014-06-20 12:00:00 -07001273// clientSessionCacheKey returns a key used to cache sessionTickets that could
1274// be used to resume previously negotiated TLS sessions with a server.
1275func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
1276 if len(config.ServerName) > 0 {
1277 return config.ServerName
1278 }
1279 return serverAddr.String()
1280}
1281
David Benjaminfa055a22014-09-15 16:51:51 -04001282// mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
1283// given list of possible protocols and a list of the preference order. The
1284// first list must not be empty. It returns the resulting protocol and flag
Adam Langley95c29f32014-06-20 12:00:00 -07001285// indicating if the fallback case was reached.
David Benjaminfa055a22014-09-15 16:51:51 -04001286func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
1287 for _, s := range preferenceProtos {
1288 for _, c := range protos {
Adam Langley95c29f32014-06-20 12:00:00 -07001289 if s == c {
1290 return s, false
1291 }
1292 }
1293 }
1294
David Benjaminfa055a22014-09-15 16:51:51 -04001295 return protos[0], true
Adam Langley95c29f32014-06-20 12:00:00 -07001296}
David Benjamind30a9902014-08-24 01:44:23 -04001297
1298// writeIntPadded writes x into b, padded up with leading zeros as
1299// needed.
1300func writeIntPadded(b []byte, x *big.Int) {
1301 for i := range b {
1302 b[i] = 0
1303 }
1304 xb := x.Bytes()
1305 copy(b[len(b)-len(xb):], xb)
1306}