blob: cb241536ec35f23f477114d1f51c4c280be6e6a8 [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"
Nick Harper0b3625b2016-07-25 16:16:28 -070021 "time"
Adam Langley95c29f32014-06-20 12:00:00 -070022)
23
24type clientHandshakeState struct {
David Benjamin83f90402015-01-27 01:09:43 -050025 c *Conn
26 serverHello *serverHelloMsg
27 hello *clientHelloMsg
28 suite *cipherSuite
29 finishedHash finishedHash
Nick Harperb41d2e42016-07-01 17:50:32 -040030 keyShares map[CurveID]ecdhCurve
David Benjamin83f90402015-01-27 01:09:43 -050031 masterSecret []byte
32 session *ClientSessionState
33 finishedBytes []byte
Adam Langley95c29f32014-06-20 12:00:00 -070034}
35
36func (c *Conn) clientHandshake() error {
37 if c.config == nil {
38 c.config = defaultConfig()
39 }
40
41 if len(c.config.ServerName) == 0 && !c.config.InsecureSkipVerify {
42 return errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
43 }
44
David Benjamin83c0bc92014-08-04 01:23:53 -040045 c.sendHandshakeSeq = 0
46 c.recvHandshakeSeq = 0
47
David Benjaminfa055a22014-09-15 16:51:51 -040048 nextProtosLength := 0
49 for _, proto := range c.config.NextProtos {
Adam Langleyefb0e162015-07-09 11:35:04 -070050 if l := len(proto); l > 255 {
David Benjaminfa055a22014-09-15 16:51:51 -040051 return errors.New("tls: invalid NextProtos value")
52 } else {
53 nextProtosLength += 1 + l
54 }
55 }
56 if nextProtosLength > 0xffff {
57 return errors.New("tls: NextProtos values too large")
58 }
59
David Benjamin3c6a1ea2016-09-26 18:30:05 -040060 maxVersion := c.config.maxVersion(c.isDTLS)
Adam Langley95c29f32014-06-20 12:00:00 -070061 hello := &clientHelloMsg{
David Benjaminca6c8262014-11-15 19:06:08 -050062 isDTLS: c.isDTLS,
David Benjamin3c6a1ea2016-09-26 18:30:05 -040063 vers: versionToWire(maxVersion, c.isDTLS),
David Benjaminca6c8262014-11-15 19:06:08 -050064 compressionMethods: []uint8{compressionNone},
65 random: make([]byte, 32),
66 ocspStapling: true,
Paul Lietar4fac72e2015-09-09 13:44:55 +010067 sctListSupported: true,
David Benjaminca6c8262014-11-15 19:06:08 -050068 serverName: c.config.ServerName,
69 supportedCurves: c.config.curvePreferences(),
70 supportedPoints: []uint8{pointFormatUncompressed},
71 nextProtoNeg: len(c.config.NextProtos) > 0,
72 secureRenegotiation: []byte{},
73 alpnProtocols: c.config.NextProtos,
74 duplicateExtension: c.config.Bugs.DuplicateExtension,
75 channelIDSupported: c.config.ChannelID != nil,
76 npnLast: c.config.Bugs.SwapNPNAndALPN,
David Benjamincecee272016-06-30 13:33:47 -040077 extendedMasterSecret: c.config.maxVersion(c.isDTLS) >= VersionTLS10,
David Benjaminca6c8262014-11-15 19:06:08 -050078 srtpProtectionProfiles: c.config.SRTPProtectionProfiles,
79 srtpMasterKeyIdentifier: c.config.Bugs.SRTPMasterKeyIdentifer,
Adam Langley09505632015-07-30 18:10:13 -070080 customExtension: c.config.Bugs.CustomExtension,
Adam Langley95c29f32014-06-20 12:00:00 -070081 }
82
David Benjamin163c9562016-08-29 23:14:17 -040083 disableEMS := c.config.Bugs.NoExtendedMasterSecret
84 if c.cipherSuite != nil {
85 disableEMS = c.config.Bugs.NoExtendedMasterSecretOnRenegotiation
86 }
87
88 if disableEMS {
Adam Langley75712922014-10-10 16:23:43 -070089 hello.extendedMasterSecret = false
90 }
91
David Benjamin55a43642015-04-20 14:45:55 -040092 if c.config.Bugs.NoSupportedCurves {
93 hello.supportedCurves = nil
94 }
95
David Benjaminc241d792016-09-09 10:34:20 -040096 if c.config.Bugs.SendCompressionMethods != nil {
97 hello.compressionMethods = c.config.Bugs.SendCompressionMethods
98 }
99
Adam Langley2ae77d22014-10-28 17:29:33 -0700100 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
101 if c.config.Bugs.BadRenegotiationInfo {
102 hello.secureRenegotiation = append(hello.secureRenegotiation, c.clientVerify...)
103 hello.secureRenegotiation[0] ^= 0x80
104 } else {
105 hello.secureRenegotiation = c.clientVerify
106 }
107 }
108
David Benjamin3e052de2015-11-25 20:10:31 -0500109 if c.noRenegotiationInfo() {
David Benjaminca6554b2014-11-08 12:31:52 -0500110 hello.secureRenegotiation = nil
111 }
112
Nick Harperb41d2e42016-07-01 17:50:32 -0400113 var keyShares map[CurveID]ecdhCurve
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400114 if maxVersion >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -0400115 keyShares = make(map[CurveID]ecdhCurve)
Nick Harperdcfbc672016-07-16 17:47:31 +0200116 hello.hasKeyShares = true
David Benjamin7e1f9842016-09-20 19:24:40 -0400117 hello.trailingKeyShareData = c.config.Bugs.TrailingKeyShareData
Nick Harperdcfbc672016-07-16 17:47:31 +0200118 curvesToSend := c.config.defaultCurves()
Nick Harperb41d2e42016-07-01 17:50:32 -0400119 for _, curveID := range hello.supportedCurves {
Nick Harperdcfbc672016-07-16 17:47:31 +0200120 if !curvesToSend[curveID] {
121 continue
122 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400123 curve, ok := curveForCurveID(curveID)
124 if !ok {
125 continue
126 }
127 publicKey, err := curve.offer(c.config.rand())
128 if err != nil {
129 return err
130 }
Steven Valdez0ee2e112016-07-15 06:51:15 -0400131
132 if c.config.Bugs.SendCurve != 0 {
133 curveID = c.config.Bugs.SendCurve
134 }
135 if c.config.Bugs.InvalidECDHPoint {
136 publicKey[0] ^= 0xff
137 }
138
Nick Harperb41d2e42016-07-01 17:50:32 -0400139 hello.keyShares = append(hello.keyShares, keyShareEntry{
140 group: curveID,
141 keyExchange: publicKey,
142 })
143 keyShares[curveID] = curve
Steven Valdez143e8b32016-07-11 13:19:03 -0400144
145 if c.config.Bugs.DuplicateKeyShares {
146 hello.keyShares = append(hello.keyShares, hello.keyShares[len(hello.keyShares)-1])
147 }
148 }
149
150 if c.config.Bugs.MissingKeyShare {
Steven Valdez5440fe02016-07-18 12:40:30 -0400151 hello.hasKeyShares = false
Nick Harperb41d2e42016-07-01 17:50:32 -0400152 }
153 }
154
Adam Langley95c29f32014-06-20 12:00:00 -0700155 possibleCipherSuites := c.config.cipherSuites()
156 hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
157
158NextCipherSuite:
159 for _, suiteId := range possibleCipherSuites {
160 for _, suite := range cipherSuites {
161 if suite.id != suiteId {
162 continue
163 }
David Benjamin0407e762016-06-17 16:41:18 -0400164 if !c.config.Bugs.EnableAllCiphers {
165 // Don't advertise TLS 1.2-only cipher suites unless
166 // we're attempting TLS 1.2.
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400167 if maxVersion < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
David Benjamin0407e762016-06-17 16:41:18 -0400168 continue
169 }
170 // Don't advertise non-DTLS cipher suites in DTLS.
171 if c.isDTLS && suite.flags&suiteNoDTLS != 0 {
172 continue
173 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400174 }
Adam Langley95c29f32014-06-20 12:00:00 -0700175 hello.cipherSuites = append(hello.cipherSuites, suiteId)
176 continue NextCipherSuite
177 }
178 }
179
Adam Langley5021b222015-06-12 18:27:58 -0700180 if c.config.Bugs.SendRenegotiationSCSV {
181 hello.cipherSuites = append(hello.cipherSuites, renegotiationSCSV)
182 }
183
David Benjaminbef270a2014-08-02 04:22:02 -0400184 if c.config.Bugs.SendFallbackSCSV {
185 hello.cipherSuites = append(hello.cipherSuites, fallbackSCSV)
186 }
187
Adam Langley95c29f32014-06-20 12:00:00 -0700188 _, err := io.ReadFull(c.config.rand(), hello.random)
189 if err != nil {
190 c.sendAlert(alertInternalError)
191 return errors.New("tls: short read from Rand: " + err.Error())
192 }
193
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400194 if maxVersion >= VersionTLS12 && !c.config.Bugs.NoSignatureAlgorithms {
David Benjamin7a41d372016-07-09 11:21:54 -0700195 hello.signatureAlgorithms = c.config.verifySignatureAlgorithms()
Adam Langley95c29f32014-06-20 12:00:00 -0700196 }
197
198 var session *ClientSessionState
199 var cacheKey string
200 sessionCache := c.config.ClientSessionCache
Adam Langley95c29f32014-06-20 12:00:00 -0700201
202 if sessionCache != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500203 hello.ticketSupported = !c.config.SessionTicketsDisabled
Adam Langley95c29f32014-06-20 12:00:00 -0700204
205 // Try to resume a previously negotiated TLS session, if
206 // available.
207 cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
Nick Harper0b3625b2016-07-25 16:16:28 -0700208 // TODO(nharper): Support storing more than one session
209 // ticket for TLS 1.3.
Adam Langley95c29f32014-06-20 12:00:00 -0700210 candidateSession, ok := sessionCache.Get(cacheKey)
211 if ok {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500212 ticketOk := !c.config.SessionTicketsDisabled || candidateSession.sessionTicket == nil
213
Adam Langley95c29f32014-06-20 12:00:00 -0700214 // Check that the ciphersuite/version used for the
215 // previous session are still valid.
216 cipherSuiteOk := false
David Benjamin46662482016-08-17 00:51:00 -0400217 if candidateSession.vers >= VersionTLS13 {
218 // Account for ciphers changing on resumption.
219 //
220 // TODO(davidben): This will be gone with the
221 // new cipher negotiation scheme.
222 resumeCipher := ecdhePSKSuite(candidateSession.cipherSuite)
223 for _, id := range hello.cipherSuites {
224 if ecdhePSKSuite(id) == resumeCipher {
225 cipherSuiteOk = true
226 break
227 }
228 }
229 } else {
230 for _, id := range hello.cipherSuites {
231 if id == candidateSession.cipherSuite {
232 cipherSuiteOk = true
233 break
234 }
Adam Langley95c29f32014-06-20 12:00:00 -0700235 }
236 }
237
David Benjamincecee272016-06-30 13:33:47 -0400238 versOk := candidateSession.vers >= c.config.minVersion(c.isDTLS) &&
239 candidateSession.vers <= c.config.maxVersion(c.isDTLS)
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500240 if ticketOk && versOk && cipherSuiteOk {
Adam Langley95c29f32014-06-20 12:00:00 -0700241 session = candidateSession
242 }
243 }
244 }
245
Nick Harper0b3625b2016-07-25 16:16:28 -0700246 if session != nil && c.config.time().Before(session.ticketExpiration) {
David Benjamind5a4ecb2016-07-18 01:17:13 +0200247 ticket := session.sessionTicket
248 if c.config.Bugs.CorruptTicket && len(ticket) > 0 {
249 ticket = make([]byte, len(session.sessionTicket))
250 copy(ticket, session.sessionTicket)
251 offset := 40
252 if offset >= len(ticket) {
253 offset = len(ticket) - 1
Adam Langley38311732014-10-16 19:04:35 -0700254 }
David Benjamind5a4ecb2016-07-18 01:17:13 +0200255 ticket[offset] ^= 0x40
256 }
257
David Benjamin405da482016-08-08 17:25:07 -0400258 if session.vers >= VersionTLS13 || c.config.Bugs.SendBothTickets {
Nick Harper0b3625b2016-07-25 16:16:28 -0700259 // TODO(nharper): Support sending more
260 // than one PSK identity.
David Benjamin405da482016-08-08 17:25:07 -0400261 if session.ticketFlags&ticketAllowDHEResumption != 0 || c.config.Bugs.SendBothTickets {
David Benjamin46662482016-08-17 00:51:00 -0400262 hello.pskIdentities = [][]uint8{ticket}
263 hello.cipherSuites = append(hello.cipherSuites, ecdhePSKSuite(session.cipherSuite))
Nick Harper0b3625b2016-07-25 16:16:28 -0700264 }
David Benjamin405da482016-08-08 17:25:07 -0400265 }
266
267 if session.vers < VersionTLS13 || c.config.Bugs.SendBothTickets {
268 if ticket != nil {
269 hello.sessionTicket = ticket
270 // A random session ID is used to detect when the
271 // server accepted the ticket and is resuming a session
272 // (see RFC 5077).
273 sessionIdLen := 16
274 if c.config.Bugs.OversizedSessionId {
275 sessionIdLen = 33
276 }
277 hello.sessionId = make([]byte, sessionIdLen)
278 if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
279 c.sendAlert(alertInternalError)
280 return errors.New("tls: short read from Rand: " + err.Error())
281 }
282 } else {
283 hello.sessionId = session.sessionId
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500284 }
Adam Langley95c29f32014-06-20 12:00:00 -0700285 }
286 }
287
David Benjamineed24012016-08-13 19:26:00 -0400288 if c.config.Bugs.SendClientVersion != 0 {
289 hello.vers = c.config.Bugs.SendClientVersion
290 }
291
David Benjamind86c7672014-08-02 04:07:12 -0400292 var helloBytes []byte
293 if c.config.Bugs.SendV2ClientHello {
David Benjamin94d701b2014-11-30 13:54:41 -0500294 // Test that the peer left-pads random.
295 hello.random[0] = 0
David Benjamind86c7672014-08-02 04:07:12 -0400296 v2Hello := &v2ClientHelloMsg{
297 vers: hello.vers,
298 cipherSuites: hello.cipherSuites,
299 // No session resumption for V2ClientHello.
300 sessionId: nil,
David Benjamin94d701b2014-11-30 13:54:41 -0500301 challenge: hello.random[1:],
David Benjamind86c7672014-08-02 04:07:12 -0400302 }
303 helloBytes = v2Hello.marshal()
304 c.writeV2Record(helloBytes)
305 } else {
306 helloBytes = hello.marshal()
David Benjamin7964b182016-07-14 23:36:30 -0400307 if c.config.Bugs.PartialClientFinishedWithClientHello {
308 // Include one byte of Finished. We can compute it
309 // without completing the handshake. This assumes we
310 // negotiate TLS 1.3 with no HelloRetryRequest or
311 // CertificateRequest.
312 toWrite := make([]byte, 0, len(helloBytes)+1)
313 toWrite = append(toWrite, helloBytes...)
314 toWrite = append(toWrite, typeFinished)
315 c.writeRecord(recordTypeHandshake, toWrite)
316 } else {
317 c.writeRecord(recordTypeHandshake, helloBytes)
318 }
David Benjamind86c7672014-08-02 04:07:12 -0400319 }
David Benjamin582ba042016-07-07 12:33:25 -0700320 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700321
David Benjamin83f90402015-01-27 01:09:43 -0500322 if err := c.simulatePacketLoss(nil); err != nil {
323 return err
324 }
Adam Langley95c29f32014-06-20 12:00:00 -0700325 msg, err := c.readHandshake()
326 if err != nil {
327 return err
328 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400329
330 if c.isDTLS {
331 helloVerifyRequest, ok := msg.(*helloVerifyRequestMsg)
332 if ok {
David Benjamin8bc38f52014-08-16 12:07:27 -0400333 if helloVerifyRequest.vers != VersionTLS10 {
334 // Per RFC 6347, the version field in
335 // HelloVerifyRequest SHOULD be always DTLS
336 // 1.0. Enforce this for testing purposes.
337 return errors.New("dtls: bad HelloVerifyRequest version")
338 }
339
David Benjamin83c0bc92014-08-04 01:23:53 -0400340 hello.raw = nil
341 hello.cookie = helloVerifyRequest.cookie
342 helloBytes = hello.marshal()
343 c.writeRecord(recordTypeHandshake, helloBytes)
David Benjamin582ba042016-07-07 12:33:25 -0700344 c.flushHandshake()
David Benjamin83c0bc92014-08-04 01:23:53 -0400345
David Benjamin83f90402015-01-27 01:09:43 -0500346 if err := c.simulatePacketLoss(nil); err != nil {
347 return err
348 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400349 msg, err = c.readHandshake()
350 if err != nil {
351 return err
352 }
353 }
354 }
355
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400356 var serverWireVersion uint16
Nick Harperdcfbc672016-07-16 17:47:31 +0200357 switch m := msg.(type) {
358 case *helloRetryRequestMsg:
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400359 serverWireVersion = m.vers
Nick Harperdcfbc672016-07-16 17:47:31 +0200360 case *serverHelloMsg:
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400361 serverWireVersion = m.vers
Nick Harperdcfbc672016-07-16 17:47:31 +0200362 default:
363 c.sendAlert(alertUnexpectedMessage)
364 return fmt.Errorf("tls: received unexpected message of type %T when waiting for HelloRetryRequest or ServerHello", msg)
365 }
366
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400367 serverVersion, ok := wireToVersion(serverWireVersion, c.isDTLS)
368 if ok {
369 c.vers, ok = c.config.mutualVersion(serverVersion, c.isDTLS)
370 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200371 if !ok {
372 c.sendAlert(alertProtocolVersion)
373 return fmt.Errorf("tls: server selected unsupported protocol version %x", c.vers)
374 }
375 c.haveVers = true
376
377 helloRetryRequest, haveHelloRetryRequest := msg.(*helloRetryRequestMsg)
378 var secondHelloBytes []byte
379 if haveHelloRetryRequest {
380 var hrrCurveFound bool
Steven Valdez5440fe02016-07-18 12:40:30 -0400381 if c.config.Bugs.MisinterpretHelloRetryRequestCurve != 0 {
382 helloRetryRequest.selectedGroup = c.config.Bugs.MisinterpretHelloRetryRequestCurve
383 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200384 group := helloRetryRequest.selectedGroup
385 for _, curveID := range hello.supportedCurves {
386 if group == curveID {
387 hrrCurveFound = true
388 break
389 }
390 }
391 if !hrrCurveFound || keyShares[group] != nil {
392 c.sendAlert(alertHandshakeFailure)
393 return errors.New("tls: received invalid HelloRetryRequest")
394 }
395 curve, ok := curveForCurveID(group)
396 if !ok {
397 return errors.New("tls: Unable to get curve requested in HelloRetryRequest")
398 }
399 publicKey, err := curve.offer(c.config.rand())
400 if err != nil {
401 return err
402 }
403 keyShares[group] = curve
404 hello.keyShares = append(hello.keyShares, keyShareEntry{
405 group: group,
406 keyExchange: publicKey,
407 })
408
Steven Valdez5440fe02016-07-18 12:40:30 -0400409 if c.config.Bugs.SecondClientHelloMissingKeyShare {
410 hello.hasKeyShares = false
411 }
412
Nick Harperdcfbc672016-07-16 17:47:31 +0200413 hello.hasEarlyData = false
414 hello.earlyDataContext = nil
415 hello.raw = nil
416
417 secondHelloBytes = hello.marshal()
418 c.writeRecord(recordTypeHandshake, secondHelloBytes)
419 c.flushHandshake()
420
421 msg, err = c.readHandshake()
422 if err != nil {
423 return err
424 }
425 }
426
Adam Langley95c29f32014-06-20 12:00:00 -0700427 serverHello, ok := msg.(*serverHelloMsg)
428 if !ok {
429 c.sendAlert(alertUnexpectedMessage)
430 return unexpectedMessageError(serverHello, msg)
431 }
432
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400433 if serverWireVersion != serverHello.vers {
Adam Langley95c29f32014-06-20 12:00:00 -0700434 c.sendAlert(alertProtocolVersion)
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400435 return fmt.Errorf("tls: server sent non-matching version %x vs %x", serverWireVersion, serverHello.vers)
Adam Langley95c29f32014-06-20 12:00:00 -0700436 }
Adam Langley95c29f32014-06-20 12:00:00 -0700437
Nick Harper85f20c22016-07-04 10:11:59 -0700438 // Check for downgrade signals in the server random, per
David Benjamin1f61f0d2016-07-10 12:20:35 -0400439 // draft-ietf-tls-tls13-14, section 6.3.1.2.
Nick Harper85f20c22016-07-04 10:11:59 -0700440 if c.vers <= VersionTLS12 && c.config.maxVersion(c.isDTLS) >= VersionTLS13 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400441 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS13) {
Nick Harper85f20c22016-07-04 10:11:59 -0700442 c.sendAlert(alertProtocolVersion)
443 return errors.New("tls: downgrade from TLS 1.3 detected")
444 }
445 }
446 if c.vers <= VersionTLS11 && c.config.maxVersion(c.isDTLS) >= VersionTLS12 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400447 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS12) {
Nick Harper85f20c22016-07-04 10:11:59 -0700448 c.sendAlert(alertProtocolVersion)
449 return errors.New("tls: downgrade from TLS 1.2 detected")
450 }
451 }
452
Nick Harper0b3625b2016-07-25 16:16:28 -0700453 suite := mutualCipherSuite(hello.cipherSuites, serverHello.cipherSuite)
Adam Langley95c29f32014-06-20 12:00:00 -0700454 if suite == nil {
455 c.sendAlert(alertHandshakeFailure)
456 return fmt.Errorf("tls: server selected an unsupported cipher suite")
457 }
458
Nick Harperdcfbc672016-07-16 17:47:31 +0200459 if haveHelloRetryRequest && (helloRetryRequest.cipherSuite != serverHello.cipherSuite || helloRetryRequest.selectedGroup != serverHello.keyShare.group) {
460 c.sendAlert(alertHandshakeFailure)
461 return errors.New("tls: ServerHello parameters did not match HelloRetryRequest")
462 }
463
Adam Langley95c29f32014-06-20 12:00:00 -0700464 hs := &clientHandshakeState{
465 c: c,
466 serverHello: serverHello,
467 hello: hello,
468 suite: suite,
469 finishedHash: newFinishedHash(c.vers, suite),
Nick Harperb41d2e42016-07-01 17:50:32 -0400470 keyShares: keyShares,
Adam Langley95c29f32014-06-20 12:00:00 -0700471 session: session,
472 }
473
David Benjamin83c0bc92014-08-04 01:23:53 -0400474 hs.writeHash(helloBytes, hs.c.sendHandshakeSeq-1)
Nick Harperdcfbc672016-07-16 17:47:31 +0200475 if haveHelloRetryRequest {
476 hs.writeServerHash(helloRetryRequest.marshal())
477 hs.writeClientHash(secondHelloBytes)
478 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400479 hs.writeServerHash(hs.serverHello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700480
David Benjamin8d315d72016-07-18 01:03:18 +0200481 if c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -0400482 if err := hs.doTLS13Handshake(); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700483 return err
484 }
485 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400486 if c.config.Bugs.EarlyChangeCipherSpec > 0 {
487 hs.establishKeys()
488 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
489 }
490
491 if hs.serverHello.compressionMethod != compressionNone {
492 c.sendAlert(alertUnexpectedMessage)
493 return errors.New("tls: server selected unsupported compression format")
494 }
495
496 err = hs.processServerExtensions(&serverHello.extensions)
497 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700498 return err
499 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400500
501 isResume, err := hs.processServerHello()
502 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700503 return err
504 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400505
506 if isResume {
507 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
508 if err := hs.establishKeys(); err != nil {
509 return err
510 }
511 }
512 if err := hs.readSessionTicket(); err != nil {
513 return err
514 }
515 if err := hs.readFinished(c.firstFinished[:]); err != nil {
516 return err
517 }
518 if err := hs.sendFinished(nil, isResume); err != nil {
519 return err
520 }
521 } else {
522 if err := hs.doFullHandshake(); err != nil {
523 return err
524 }
525 if err := hs.establishKeys(); err != nil {
526 return err
527 }
528 if err := hs.sendFinished(c.firstFinished[:], isResume); err != nil {
529 return err
530 }
531 // Most retransmits are triggered by a timeout, but the final
532 // leg of the handshake is retransmited upon re-receiving a
533 // Finished.
534 if err := c.simulatePacketLoss(func() {
David Benjamin02edcd02016-07-27 17:40:37 -0400535 c.sendHandshakeSeq--
Nick Harperb41d2e42016-07-01 17:50:32 -0400536 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
537 c.flushHandshake()
538 }); err != nil {
539 return err
540 }
541 if err := hs.readSessionTicket(); err != nil {
542 return err
543 }
544 if err := hs.readFinished(nil); err != nil {
545 return err
546 }
Adam Langley95c29f32014-06-20 12:00:00 -0700547 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400548
549 if sessionCache != nil && hs.session != nil && session != hs.session {
550 if c.config.Bugs.RequireSessionTickets && len(hs.session.sessionTicket) == 0 {
551 return errors.New("tls: new session used session IDs instead of tickets")
552 }
553 sessionCache.Put(cacheKey, hs.session)
David Benjamin83f90402015-01-27 01:09:43 -0500554 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400555
556 c.didResume = isResume
David Benjamin97a0a082016-07-13 17:57:35 -0400557 c.exporterSecret = hs.masterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700558 }
559
Adam Langley95c29f32014-06-20 12:00:00 -0700560 c.handshakeComplete = true
David Benjaminc565ebb2015-04-03 04:06:36 -0400561 c.cipherSuite = suite
562 copy(c.clientRandom[:], hs.hello.random)
563 copy(c.serverRandom[:], hs.serverHello.random)
Paul Lietar4fac72e2015-09-09 13:44:55 +0100564
Adam Langley95c29f32014-06-20 12:00:00 -0700565 return nil
566}
567
Nick Harperb41d2e42016-07-01 17:50:32 -0400568func (hs *clientHandshakeState) doTLS13Handshake() error {
569 c := hs.c
570
571 // Once the PRF hash is known, TLS 1.3 does not require a handshake
572 // buffer.
573 hs.finishedHash.discardHandshakeBuffer()
574
575 zeroSecret := hs.finishedHash.zeroSecret()
576
577 // Resolve PSK and compute the early secret.
578 //
579 // TODO(davidben): This will need to be handled slightly earlier once
580 // 0-RTT is implemented.
581 var psk []byte
582 if hs.suite.flags&suitePSK != 0 {
583 if !hs.serverHello.hasPSKIdentity {
584 c.sendAlert(alertMissingExtension)
585 return errors.New("tls: server omitted the PSK identity extension")
586 }
587
Nick Harper0b3625b2016-07-25 16:16:28 -0700588 // We send at most one PSK identity.
589 if hs.session == nil || hs.serverHello.pskIdentity != 0 {
590 c.sendAlert(alertUnknownPSKIdentity)
591 return errors.New("tls: server sent unknown PSK identity")
592 }
593 if ecdhePSKSuite(hs.session.cipherSuite) != hs.suite.id {
594 c.sendAlert(alertHandshakeFailure)
595 return errors.New("tls: server sent invalid cipher suite for PSK")
596 }
597 psk = deriveResumptionPSK(hs.suite, hs.session.masterSecret)
598 hs.finishedHash.setResumptionContext(deriveResumptionContext(hs.suite, hs.session.masterSecret))
599 c.didResume = true
Nick Harperb41d2e42016-07-01 17:50:32 -0400600 } else {
601 if hs.serverHello.hasPSKIdentity {
602 c.sendAlert(alertUnsupportedExtension)
603 return errors.New("tls: server sent unexpected PSK identity")
604 }
605
606 psk = zeroSecret
607 hs.finishedHash.setResumptionContext(zeroSecret)
608 }
609
610 earlySecret := hs.finishedHash.extractKey(zeroSecret, psk)
611
612 // Resolve ECDHE and compute the handshake secret.
613 var ecdheSecret []byte
Steven Valdez5440fe02016-07-18 12:40:30 -0400614 if hs.suite.flags&suiteECDHE != 0 && !c.config.Bugs.MissingKeyShare && !c.config.Bugs.SecondClientHelloMissingKeyShare {
Nick Harperb41d2e42016-07-01 17:50:32 -0400615 if !hs.serverHello.hasKeyShare {
616 c.sendAlert(alertMissingExtension)
617 return errors.New("tls: server omitted the key share extension")
618 }
619
620 curve, ok := hs.keyShares[hs.serverHello.keyShare.group]
621 if !ok {
622 c.sendAlert(alertHandshakeFailure)
623 return errors.New("tls: server selected an unsupported group")
624 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400625 c.curveID = hs.serverHello.keyShare.group
Nick Harperb41d2e42016-07-01 17:50:32 -0400626
627 var err error
628 ecdheSecret, err = curve.finish(hs.serverHello.keyShare.keyExchange)
629 if err != nil {
630 return err
631 }
632 } else {
633 if hs.serverHello.hasKeyShare {
634 c.sendAlert(alertUnsupportedExtension)
635 return errors.New("tls: server sent unexpected key share extension")
636 }
637
638 ecdheSecret = zeroSecret
639 }
640
641 // Compute the handshake secret.
642 handshakeSecret := hs.finishedHash.extractKey(earlySecret, ecdheSecret)
643
644 // Switch to handshake traffic keys.
645 handshakeTrafficSecret := hs.finishedHash.deriveSecret(handshakeSecret, handshakeTrafficLabel)
David Benjamin21c00282016-07-18 21:56:23 +0200646 c.out.useTrafficSecret(c.vers, hs.suite, handshakeTrafficSecret, handshakePhase, clientWrite)
647 c.in.useTrafficSecret(c.vers, hs.suite, handshakeTrafficSecret, handshakePhase, serverWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -0400648
649 msg, err := c.readHandshake()
650 if err != nil {
651 return err
652 }
653
654 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
655 if !ok {
656 c.sendAlert(alertUnexpectedMessage)
657 return unexpectedMessageError(encryptedExtensions, msg)
658 }
659 hs.writeServerHash(encryptedExtensions.marshal())
660
661 err = hs.processServerExtensions(&encryptedExtensions.extensions)
662 if err != nil {
663 return err
664 }
665
666 var chainToSend *Certificate
David Benjamin8d343b42016-07-09 14:26:01 -0700667 var certReq *certificateRequestMsg
David Benjamin44b33bc2016-07-01 22:40:23 -0400668 if hs.suite.flags&suitePSK != 0 {
669 if encryptedExtensions.extensions.ocspResponse != nil {
670 c.sendAlert(alertUnsupportedExtension)
671 return errors.New("tls: server sent OCSP response without a certificate")
672 }
673 if encryptedExtensions.extensions.sctList != nil {
674 c.sendAlert(alertUnsupportedExtension)
675 return errors.New("tls: server sent SCT list without a certificate")
676 }
Nick Harper0b3625b2016-07-25 16:16:28 -0700677
678 // Copy over authentication from the session.
679 c.peerCertificates = hs.session.serverCertificates
680 c.sctList = hs.session.sctList
681 c.ocspResponse = hs.session.ocspResponse
David Benjamin44b33bc2016-07-01 22:40:23 -0400682 } else {
683 c.ocspResponse = encryptedExtensions.extensions.ocspResponse
684 c.sctList = encryptedExtensions.extensions.sctList
Nick Harperb41d2e42016-07-01 17:50:32 -0400685
686 msg, err := c.readHandshake()
687 if err != nil {
688 return err
689 }
690
David Benjamin8d343b42016-07-09 14:26:01 -0700691 var ok bool
692 certReq, ok = msg.(*certificateRequestMsg)
Nick Harperb41d2e42016-07-01 17:50:32 -0400693 if ok {
David Benjamin8a8349b2016-08-18 02:32:23 -0400694 if len(certReq.requestContext) != 0 {
695 return errors.New("tls: non-empty certificate request context sent in handshake")
696 }
697
David Benjaminb62d2872016-07-18 14:55:02 +0200698 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
699 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
700 }
701
Nick Harperb41d2e42016-07-01 17:50:32 -0400702 hs.writeServerHash(certReq.marshal())
Nick Harperb41d2e42016-07-01 17:50:32 -0400703
704 chainToSend, err = selectClientCertificate(c, certReq)
705 if err != nil {
706 return err
707 }
708
709 msg, err = c.readHandshake()
710 if err != nil {
711 return err
712 }
713 }
714
715 certMsg, ok := msg.(*certificateMsg)
716 if !ok {
717 c.sendAlert(alertUnexpectedMessage)
718 return unexpectedMessageError(certMsg, msg)
719 }
720 hs.writeServerHash(certMsg.marshal())
721
722 if err := hs.verifyCertificates(certMsg); err != nil {
723 return err
724 }
725 leaf := c.peerCertificates[0]
726
727 msg, err = c.readHandshake()
728 if err != nil {
729 return err
730 }
731 certVerifyMsg, ok := msg.(*certificateVerifyMsg)
732 if !ok {
733 c.sendAlert(alertUnexpectedMessage)
734 return unexpectedMessageError(certVerifyMsg, msg)
735 }
736
David Benjaminf74ec792016-07-13 21:18:49 -0400737 c.peerSignatureAlgorithm = certVerifyMsg.signatureAlgorithm
Nick Harperb41d2e42016-07-01 17:50:32 -0400738 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
David Benjamin1fb125c2016-07-08 18:52:12 -0700739 err = verifyMessage(c.vers, leaf.PublicKey, c.config, certVerifyMsg.signatureAlgorithm, input, certVerifyMsg.signature)
Nick Harperb41d2e42016-07-01 17:50:32 -0400740 if err != nil {
741 return err
742 }
743
744 hs.writeServerHash(certVerifyMsg.marshal())
745 }
746
747 msg, err = c.readHandshake()
748 if err != nil {
749 return err
750 }
751 serverFinished, ok := msg.(*finishedMsg)
752 if !ok {
753 c.sendAlert(alertUnexpectedMessage)
754 return unexpectedMessageError(serverFinished, msg)
755 }
756
757 verify := hs.finishedHash.serverSum(handshakeTrafficSecret)
758 if len(verify) != len(serverFinished.verifyData) ||
759 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
760 c.sendAlert(alertHandshakeFailure)
761 return errors.New("tls: server's Finished message was incorrect")
762 }
763
764 hs.writeServerHash(serverFinished.marshal())
765
766 // The various secrets do not incorporate the client's final leg, so
767 // derive them now before updating the handshake context.
768 masterSecret := hs.finishedHash.extractKey(handshakeSecret, zeroSecret)
769 trafficSecret := hs.finishedHash.deriveSecret(masterSecret, applicationTrafficLabel)
770
Steven Valdez0ee2e112016-07-15 06:51:15 -0400771 if certReq != nil && !c.config.Bugs.SkipClientCertificate {
David Benjamin8d343b42016-07-09 14:26:01 -0700772 certMsg := &certificateMsg{
773 hasRequestContext: true,
774 requestContext: certReq.requestContext,
775 }
776 if chainToSend != nil {
777 certMsg.certificates = chainToSend.Certificate
778 }
779 hs.writeClientHash(certMsg.marshal())
780 c.writeRecord(recordTypeHandshake, certMsg.marshal())
781
782 if chainToSend != nil {
783 certVerify := &certificateVerifyMsg{
784 hasSignatureAlgorithm: true,
785 }
786
787 // Determine the hash to sign.
788 privKey := chainToSend.PrivateKey
789
790 var err error
791 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
792 if err != nil {
793 c.sendAlert(alertInternalError)
794 return err
795 }
796
797 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
798 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
799 if err != nil {
800 c.sendAlert(alertInternalError)
801 return err
802 }
Steven Valdez0ee2e112016-07-15 06:51:15 -0400803 if c.config.Bugs.SendSignatureAlgorithm != 0 {
804 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
805 }
David Benjamin8d343b42016-07-09 14:26:01 -0700806
807 hs.writeClientHash(certVerify.marshal())
808 c.writeRecord(recordTypeHandshake, certVerify.marshal())
809 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400810 }
811
812 // Send a client Finished message.
813 finished := new(finishedMsg)
814 finished.verifyData = hs.finishedHash.clientSum(handshakeTrafficSecret)
815 if c.config.Bugs.BadFinished {
816 finished.verifyData[0]++
817 }
David Benjamin97a0a082016-07-13 17:57:35 -0400818 hs.writeClientHash(finished.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400819 if c.config.Bugs.PartialClientFinishedWithClientHello {
820 // The first byte has already been sent.
821 c.writeRecord(recordTypeHandshake, finished.marshal()[1:])
822 } else {
823 c.writeRecord(recordTypeHandshake, finished.marshal())
824 }
David Benjamin02edcd02016-07-27 17:40:37 -0400825 if c.config.Bugs.SendExtraFinished {
826 c.writeRecord(recordTypeHandshake, finished.marshal())
827 }
David Benjaminee51a222016-07-07 18:34:12 -0700828 c.flushHandshake()
Nick Harperb41d2e42016-07-01 17:50:32 -0400829
830 // Switch to application data keys.
David Benjamin21c00282016-07-18 21:56:23 +0200831 c.out.useTrafficSecret(c.vers, hs.suite, trafficSecret, applicationPhase, clientWrite)
832 c.in.useTrafficSecret(c.vers, hs.suite, trafficSecret, applicationPhase, serverWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -0400833
David Benjamin97a0a082016-07-13 17:57:35 -0400834 c.exporterSecret = hs.finishedHash.deriveSecret(masterSecret, exporterLabel)
David Benjamind5a4ecb2016-07-18 01:17:13 +0200835 c.resumptionSecret = hs.finishedHash.deriveSecret(masterSecret, resumptionLabel)
Nick Harperb41d2e42016-07-01 17:50:32 -0400836 return nil
837}
838
Adam Langley95c29f32014-06-20 12:00:00 -0700839func (hs *clientHandshakeState) doFullHandshake() error {
840 c := hs.c
841
David Benjamin48cae082014-10-27 01:06:24 -0400842 var leaf *x509.Certificate
843 if hs.suite.flags&suitePSK == 0 {
844 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700845 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700846 return err
847 }
Adam Langley95c29f32014-06-20 12:00:00 -0700848
David Benjamin48cae082014-10-27 01:06:24 -0400849 certMsg, ok := msg.(*certificateMsg)
David Benjamin75051442016-07-01 18:58:51 -0400850 if !ok {
David Benjamin48cae082014-10-27 01:06:24 -0400851 c.sendAlert(alertUnexpectedMessage)
852 return unexpectedMessageError(certMsg, msg)
853 }
854 hs.writeServerHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700855
David Benjamin75051442016-07-01 18:58:51 -0400856 if err := hs.verifyCertificates(certMsg); err != nil {
857 return err
David Benjamin48cae082014-10-27 01:06:24 -0400858 }
David Benjamin75051442016-07-01 18:58:51 -0400859 leaf = c.peerCertificates[0]
David Benjamin48cae082014-10-27 01:06:24 -0400860 }
Adam Langley95c29f32014-06-20 12:00:00 -0700861
Nick Harperb3d51be2016-07-01 11:43:18 -0400862 if hs.serverHello.extensions.ocspStapling {
David Benjamin48cae082014-10-27 01:06:24 -0400863 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700864 if err != nil {
865 return err
866 }
867 cs, ok := msg.(*certificateStatusMsg)
868 if !ok {
869 c.sendAlert(alertUnexpectedMessage)
870 return unexpectedMessageError(cs, msg)
871 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400872 hs.writeServerHash(cs.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700873
874 if cs.statusType == statusTypeOCSP {
875 c.ocspResponse = cs.response
876 }
877 }
878
David Benjamin48cae082014-10-27 01:06:24 -0400879 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700880 if err != nil {
881 return err
882 }
883
884 keyAgreement := hs.suite.ka(c.vers)
885
886 skx, ok := msg.(*serverKeyExchangeMsg)
887 if ok {
David Benjamin83c0bc92014-08-04 01:23:53 -0400888 hs.writeServerHash(skx.marshal())
David Benjamin48cae082014-10-27 01:06:24 -0400889 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, leaf, skx)
Adam Langley95c29f32014-06-20 12:00:00 -0700890 if err != nil {
891 c.sendAlert(alertUnexpectedMessage)
892 return err
893 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400894 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
895 c.curveID = ecdhe.curveID
896 }
Adam Langley95c29f32014-06-20 12:00:00 -0700897
Nick Harper60edffd2016-06-21 15:19:24 -0700898 c.peerSignatureAlgorithm = keyAgreement.peerSignatureAlgorithm()
899
Adam Langley95c29f32014-06-20 12:00:00 -0700900 msg, err = c.readHandshake()
901 if err != nil {
902 return err
903 }
904 }
905
906 var chainToSend *Certificate
907 var certRequested bool
908 certReq, ok := msg.(*certificateRequestMsg)
909 if ok {
910 certRequested = true
David Benjamin7a41d372016-07-09 11:21:54 -0700911 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
912 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
913 }
Adam Langley95c29f32014-06-20 12:00:00 -0700914
David Benjamin83c0bc92014-08-04 01:23:53 -0400915 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700916
David Benjamina6f82632016-07-01 18:44:02 -0400917 chainToSend, err = selectClientCertificate(c, certReq)
918 if err != nil {
919 return err
Adam Langley95c29f32014-06-20 12:00:00 -0700920 }
921
922 msg, err = c.readHandshake()
923 if err != nil {
924 return err
925 }
926 }
927
928 shd, ok := msg.(*serverHelloDoneMsg)
929 if !ok {
930 c.sendAlert(alertUnexpectedMessage)
931 return unexpectedMessageError(shd, msg)
932 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400933 hs.writeServerHash(shd.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700934
935 // If the server requested a certificate then we have to send a
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500936 // Certificate message in TLS, even if it's empty because we don't have
937 // a certificate to send. In SSL 3.0, skip the message and send a
938 // no_certificate warning alert.
Adam Langley95c29f32014-06-20 12:00:00 -0700939 if certRequested {
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500940 if c.vers == VersionSSL30 && chainToSend == nil {
941 c.sendAlert(alertNoCertficate)
942 } else if !c.config.Bugs.SkipClientCertificate {
943 certMsg := new(certificateMsg)
944 if chainToSend != nil {
945 certMsg.certificates = chainToSend.Certificate
946 }
947 hs.writeClientHash(certMsg.marshal())
948 c.writeRecord(recordTypeHandshake, certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700949 }
Adam Langley95c29f32014-06-20 12:00:00 -0700950 }
951
David Benjamin48cae082014-10-27 01:06:24 -0400952 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, leaf)
Adam Langley95c29f32014-06-20 12:00:00 -0700953 if err != nil {
954 c.sendAlert(alertInternalError)
955 return err
956 }
957 if ckx != nil {
David Benjaminf3ec83d2014-07-21 22:42:34 -0400958 if c.config.Bugs.EarlyChangeCipherSpec < 2 {
David Benjamin83c0bc92014-08-04 01:23:53 -0400959 hs.writeClientHash(ckx.marshal())
David Benjaminf3ec83d2014-07-21 22:42:34 -0400960 }
Adam Langley95c29f32014-06-20 12:00:00 -0700961 c.writeRecord(recordTypeHandshake, ckx.marshal())
962 }
963
Nick Harperb3d51be2016-07-01 11:43:18 -0400964 if hs.serverHello.extensions.extendedMasterSecret && c.vers >= VersionTLS10 {
Adam Langley75712922014-10-10 16:23:43 -0700965 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
966 c.extendedMasterSecret = true
967 } else {
968 if c.config.Bugs.RequireExtendedMasterSecret {
969 return errors.New("tls: extended master secret required but not supported by peer")
970 }
971 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
972 }
David Benjamine098ec22014-08-27 23:13:20 -0400973
Adam Langley95c29f32014-06-20 12:00:00 -0700974 if chainToSend != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700975 certVerify := &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -0700976 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -0700977 }
978
David Benjamin72dc7832015-03-16 17:49:43 -0400979 // Determine the hash to sign.
Nick Harper60edffd2016-06-21 15:19:24 -0700980 privKey := c.config.Certificates[0].PrivateKey
David Benjamin72dc7832015-03-16 17:49:43 -0400981
Nick Harper60edffd2016-06-21 15:19:24 -0700982 if certVerify.hasSignatureAlgorithm {
David Benjamin0a8deb22016-07-09 21:02:01 -0700983 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
Nick Harper60edffd2016-06-21 15:19:24 -0700984 if err != nil {
985 c.sendAlert(alertInternalError)
986 return err
Adam Langley95c29f32014-06-20 12:00:00 -0700987 }
Nick Harper60edffd2016-06-21 15:19:24 -0700988 }
989
990 if c.vers > VersionSSL30 {
David Benjamin5208fd42016-07-13 21:43:25 -0400991 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, hs.finishedHash.buffer)
David Benjamina95e9f32016-07-08 16:28:04 -0700992 if err == nil && c.config.Bugs.SendSignatureAlgorithm != 0 {
993 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
994 }
Nick Harper60edffd2016-06-21 15:19:24 -0700995 } else {
996 // SSL 3.0's client certificate construction is
997 // incompatible with signatureAlgorithm.
998 rsaKey, ok := privKey.(*rsa.PrivateKey)
999 if !ok {
1000 err = errors.New("unsupported signature type for client certificate")
1001 } else {
1002 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
David Benjamin5208fd42016-07-13 21:43:25 -04001003 if c.config.Bugs.InvalidSignature {
Nick Harper60edffd2016-06-21 15:19:24 -07001004 digest[0] ^= 0x80
1005 }
1006 certVerify.signature, err = rsa.SignPKCS1v15(c.config.rand(), rsaKey, crypto.MD5SHA1, digest)
1007 }
Adam Langley95c29f32014-06-20 12:00:00 -07001008 }
1009 if err != nil {
1010 c.sendAlert(alertInternalError)
1011 return errors.New("tls: failed to sign handshake with client certificate: " + err.Error())
1012 }
Adam Langley95c29f32014-06-20 12:00:00 -07001013
David Benjamin83c0bc92014-08-04 01:23:53 -04001014 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001015 c.writeRecord(recordTypeHandshake, certVerify.marshal())
1016 }
David Benjamin82261be2016-07-07 14:32:50 -07001017 // flushHandshake will be called in sendFinished.
Adam Langley95c29f32014-06-20 12:00:00 -07001018
David Benjamine098ec22014-08-27 23:13:20 -04001019 hs.finishedHash.discardHandshakeBuffer()
1020
Adam Langley95c29f32014-06-20 12:00:00 -07001021 return nil
1022}
1023
David Benjamin75051442016-07-01 18:58:51 -04001024func (hs *clientHandshakeState) verifyCertificates(certMsg *certificateMsg) error {
1025 c := hs.c
1026
1027 if len(certMsg.certificates) == 0 {
1028 c.sendAlert(alertIllegalParameter)
1029 return errors.New("tls: no certificates sent")
1030 }
1031
1032 certs := make([]*x509.Certificate, len(certMsg.certificates))
1033 for i, asn1Data := range certMsg.certificates {
1034 cert, err := x509.ParseCertificate(asn1Data)
1035 if err != nil {
1036 c.sendAlert(alertBadCertificate)
1037 return errors.New("tls: failed to parse certificate from server: " + err.Error())
1038 }
1039 certs[i] = cert
1040 }
1041
1042 if !c.config.InsecureSkipVerify {
1043 opts := x509.VerifyOptions{
1044 Roots: c.config.RootCAs,
1045 CurrentTime: c.config.time(),
1046 DNSName: c.config.ServerName,
1047 Intermediates: x509.NewCertPool(),
1048 }
1049
1050 for i, cert := range certs {
1051 if i == 0 {
1052 continue
1053 }
1054 opts.Intermediates.AddCert(cert)
1055 }
1056 var err error
1057 c.verifiedChains, err = certs[0].Verify(opts)
1058 if err != nil {
1059 c.sendAlert(alertBadCertificate)
1060 return err
1061 }
1062 }
1063
1064 switch certs[0].PublicKey.(type) {
1065 case *rsa.PublicKey, *ecdsa.PublicKey:
1066 break
1067 default:
1068 c.sendAlert(alertUnsupportedCertificate)
1069 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
1070 }
1071
1072 c.peerCertificates = certs
1073 return nil
1074}
1075
Adam Langley95c29f32014-06-20 12:00:00 -07001076func (hs *clientHandshakeState) establishKeys() error {
1077 c := hs.c
1078
1079 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001080 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 -07001081 var clientCipher, serverCipher interface{}
1082 var clientHash, serverHash macFunction
1083 if hs.suite.cipher != nil {
1084 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
1085 clientHash = hs.suite.mac(c.vers, clientMAC)
1086 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
1087 serverHash = hs.suite.mac(c.vers, serverMAC)
1088 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001089 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1090 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001091 }
1092
1093 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
1094 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
1095 return nil
1096}
1097
David Benjamin75101402016-07-01 13:40:23 -04001098func (hs *clientHandshakeState) processServerExtensions(serverExtensions *serverExtensions) error {
1099 c := hs.c
1100
David Benjamin8d315d72016-07-18 01:03:18 +02001101 if c.vers < VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001102 if c.config.Bugs.RequireRenegotiationInfo && serverExtensions.secureRenegotiation == nil {
1103 return errors.New("tls: renegotiation extension missing")
1104 }
David Benjamin75101402016-07-01 13:40:23 -04001105
Nick Harperb41d2e42016-07-01 17:50:32 -04001106 if len(c.clientVerify) > 0 && !c.noRenegotiationInfo() {
1107 var expectedRenegInfo []byte
1108 expectedRenegInfo = append(expectedRenegInfo, c.clientVerify...)
1109 expectedRenegInfo = append(expectedRenegInfo, c.serverVerify...)
1110 if !bytes.Equal(serverExtensions.secureRenegotiation, expectedRenegInfo) {
1111 c.sendAlert(alertHandshakeFailure)
1112 return fmt.Errorf("tls: renegotiation mismatch")
1113 }
David Benjamin75101402016-07-01 13:40:23 -04001114 }
David Benjamincea0ab42016-07-14 12:33:14 -04001115 } else if serverExtensions.secureRenegotiation != nil {
1116 return errors.New("tls: renegotiation info sent in TLS 1.3")
David Benjamin75101402016-07-01 13:40:23 -04001117 }
1118
1119 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
1120 if serverExtensions.customExtension != *expected {
1121 return fmt.Errorf("tls: bad custom extension contents %q", serverExtensions.customExtension)
1122 }
1123 }
1124
1125 clientDidNPN := hs.hello.nextProtoNeg
1126 clientDidALPN := len(hs.hello.alpnProtocols) > 0
1127 serverHasNPN := serverExtensions.nextProtoNeg
1128 serverHasALPN := len(serverExtensions.alpnProtocol) > 0
1129
1130 if !clientDidNPN && serverHasNPN {
1131 c.sendAlert(alertHandshakeFailure)
1132 return errors.New("server advertised unrequested NPN extension")
1133 }
1134
1135 if !clientDidALPN && serverHasALPN {
1136 c.sendAlert(alertHandshakeFailure)
1137 return errors.New("server advertised unrequested ALPN extension")
1138 }
1139
1140 if serverHasNPN && serverHasALPN {
1141 c.sendAlert(alertHandshakeFailure)
1142 return errors.New("server advertised both NPN and ALPN extensions")
1143 }
1144
1145 if serverHasALPN {
1146 c.clientProtocol = serverExtensions.alpnProtocol
1147 c.clientProtocolFallback = false
1148 c.usedALPN = true
1149 }
1150
David Benjamin8d315d72016-07-18 01:03:18 +02001151 if serverHasNPN && c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001152 c.sendAlert(alertHandshakeFailure)
1153 return errors.New("server advertised NPN over TLS 1.3")
1154 }
1155
David Benjamin75101402016-07-01 13:40:23 -04001156 if !hs.hello.channelIDSupported && serverExtensions.channelIDRequested {
1157 c.sendAlert(alertHandshakeFailure)
1158 return errors.New("server advertised unrequested Channel ID extension")
1159 }
1160
David Benjamin8d315d72016-07-18 01:03:18 +02001161 if serverExtensions.channelIDRequested && c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001162 c.sendAlert(alertHandshakeFailure)
1163 return errors.New("server advertised Channel ID over TLS 1.3")
1164 }
1165
David Benjamin8d315d72016-07-18 01:03:18 +02001166 if serverExtensions.extendedMasterSecret && c.vers >= VersionTLS13 {
David Benjamine9077652016-07-13 21:02:08 -04001167 return errors.New("tls: server advertised extended master secret over TLS 1.3")
1168 }
1169
David Benjamin8d315d72016-07-18 01:03:18 +02001170 if serverExtensions.ticketSupported && c.vers >= VersionTLS13 {
Steven Valdez143e8b32016-07-11 13:19:03 -04001171 return errors.New("tls: server advertised ticket extension over TLS 1.3")
1172 }
1173
David Benjamin75101402016-07-01 13:40:23 -04001174 if serverExtensions.srtpProtectionProfile != 0 {
1175 if serverExtensions.srtpMasterKeyIdentifier != "" {
1176 return errors.New("tls: server selected SRTP MKI value")
1177 }
1178
1179 found := false
1180 for _, p := range c.config.SRTPProtectionProfiles {
1181 if p == serverExtensions.srtpProtectionProfile {
1182 found = true
1183 break
1184 }
1185 }
1186 if !found {
1187 return errors.New("tls: server advertised unsupported SRTP profile")
1188 }
1189
1190 c.srtpProtectionProfile = serverExtensions.srtpProtectionProfile
1191 }
1192
1193 return nil
1194}
1195
Adam Langley95c29f32014-06-20 12:00:00 -07001196func (hs *clientHandshakeState) serverResumedSession() bool {
1197 // If the server responded with the same sessionId then it means the
1198 // sessionTicket is being used to resume a TLS session.
1199 return hs.session != nil && hs.hello.sessionId != nil &&
1200 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
1201}
1202
1203func (hs *clientHandshakeState) processServerHello() (bool, error) {
1204 c := hs.c
1205
Adam Langley95c29f32014-06-20 12:00:00 -07001206 if hs.serverResumedSession() {
David Benjamin4b27d9f2015-05-12 22:42:52 -04001207 // For test purposes, assert that the server never accepts the
1208 // resumption offer on renegotiation.
1209 if c.cipherSuite != nil && c.config.Bugs.FailIfResumeOnRenego {
1210 return false, errors.New("tls: server resumed session on renegotiation")
1211 }
1212
Nick Harperb3d51be2016-07-01 11:43:18 -04001213 if hs.serverHello.extensions.sctList != nil {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001214 return false, errors.New("tls: server sent SCT extension on session resumption")
1215 }
1216
Nick Harperb3d51be2016-07-01 11:43:18 -04001217 if hs.serverHello.extensions.ocspStapling {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001218 return false, errors.New("tls: server sent OCSP extension on session resumption")
1219 }
1220
Adam Langley95c29f32014-06-20 12:00:00 -07001221 // Restore masterSecret and peerCerts from previous state
1222 hs.masterSecret = hs.session.masterSecret
1223 c.peerCertificates = hs.session.serverCertificates
Adam Langley75712922014-10-10 16:23:43 -07001224 c.extendedMasterSecret = hs.session.extendedMasterSecret
Paul Lietar62be8ac2015-09-16 10:03:30 +01001225 c.sctList = hs.session.sctList
1226 c.ocspResponse = hs.session.ocspResponse
David Benjamine098ec22014-08-27 23:13:20 -04001227 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001228 return true, nil
1229 }
Paul Lietar62be8ac2015-09-16 10:03:30 +01001230
Nick Harperb3d51be2016-07-01 11:43:18 -04001231 if hs.serverHello.extensions.sctList != nil {
1232 c.sctList = hs.serverHello.extensions.sctList
Paul Lietar62be8ac2015-09-16 10:03:30 +01001233 }
1234
Adam Langley95c29f32014-06-20 12:00:00 -07001235 return false, nil
1236}
1237
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001238func (hs *clientHandshakeState) readFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001239 c := hs.c
1240
1241 c.readRecord(recordTypeChangeCipherSpec)
1242 if err := c.in.error(); err != nil {
1243 return err
1244 }
1245
1246 msg, err := c.readHandshake()
1247 if err != nil {
1248 return err
1249 }
1250 serverFinished, ok := msg.(*finishedMsg)
1251 if !ok {
1252 c.sendAlert(alertUnexpectedMessage)
1253 return unexpectedMessageError(serverFinished, msg)
1254 }
1255
David Benjaminf3ec83d2014-07-21 22:42:34 -04001256 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
1257 verify := hs.finishedHash.serverSum(hs.masterSecret)
1258 if len(verify) != len(serverFinished.verifyData) ||
1259 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
1260 c.sendAlert(alertHandshakeFailure)
1261 return errors.New("tls: server's Finished message was incorrect")
1262 }
Adam Langley95c29f32014-06-20 12:00:00 -07001263 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001264 c.serverVerify = append(c.serverVerify[:0], serverFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001265 copy(out, serverFinished.verifyData)
David Benjamin83c0bc92014-08-04 01:23:53 -04001266 hs.writeServerHash(serverFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001267 return nil
1268}
1269
1270func (hs *clientHandshakeState) readSessionTicket() error {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001271 c := hs.c
1272
1273 // Create a session with no server identifier. Either a
1274 // session ID or session ticket will be attached.
1275 session := &ClientSessionState{
1276 vers: c.vers,
1277 cipherSuite: hs.suite.id,
1278 masterSecret: hs.masterSecret,
1279 handshakeHash: hs.finishedHash.server.Sum(nil),
1280 serverCertificates: c.peerCertificates,
Paul Lietar62be8ac2015-09-16 10:03:30 +01001281 sctList: c.sctList,
1282 ocspResponse: c.ocspResponse,
Nick Harper0b3625b2016-07-25 16:16:28 -07001283 ticketExpiration: c.config.time().Add(time.Duration(7 * 24 * time.Hour)),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001284 }
1285
Nick Harperb3d51be2016-07-01 11:43:18 -04001286 if !hs.serverHello.extensions.ticketSupported {
David Benjamind98452d2015-06-16 14:16:23 -04001287 if c.config.Bugs.ExpectNewTicket {
1288 return errors.New("tls: expected new ticket")
1289 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001290 if hs.session == nil && len(hs.serverHello.sessionId) > 0 {
1291 session.sessionId = hs.serverHello.sessionId
1292 hs.session = session
1293 }
Adam Langley95c29f32014-06-20 12:00:00 -07001294 return nil
1295 }
1296
David Benjaminc7ce9772015-10-09 19:32:41 -04001297 if c.vers == VersionSSL30 {
1298 return errors.New("tls: negotiated session tickets in SSL 3.0")
1299 }
1300
Adam Langley95c29f32014-06-20 12:00:00 -07001301 msg, err := c.readHandshake()
1302 if err != nil {
1303 return err
1304 }
1305 sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
1306 if !ok {
1307 c.sendAlert(alertUnexpectedMessage)
1308 return unexpectedMessageError(sessionTicketMsg, msg)
1309 }
Adam Langley95c29f32014-06-20 12:00:00 -07001310
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001311 session.sessionTicket = sessionTicketMsg.ticket
1312 hs.session = session
Adam Langley95c29f32014-06-20 12:00:00 -07001313
David Benjamind30a9902014-08-24 01:44:23 -04001314 hs.writeServerHash(sessionTicketMsg.marshal())
1315
Adam Langley95c29f32014-06-20 12:00:00 -07001316 return nil
1317}
1318
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001319func (hs *clientHandshakeState) sendFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001320 c := hs.c
1321
David Benjamin0b8d5da2016-07-15 00:39:56 -04001322 var postCCSMsgs [][]byte
David Benjamin83c0bc92014-08-04 01:23:53 -04001323 seqno := hs.c.sendHandshakeSeq
Nick Harperb3d51be2016-07-01 11:43:18 -04001324 if hs.serverHello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001325 nextProto := new(nextProtoMsg)
Nick Harperb3d51be2016-07-01 11:43:18 -04001326 proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.extensions.nextProtos)
Adam Langley95c29f32014-06-20 12:00:00 -07001327 nextProto.proto = proto
1328 c.clientProtocol = proto
1329 c.clientProtocolFallback = fallback
1330
David Benjamin86271ee2014-07-21 16:14:03 -04001331 nextProtoBytes := nextProto.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -04001332 hs.writeHash(nextProtoBytes, seqno)
1333 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001334 postCCSMsgs = append(postCCSMsgs, nextProtoBytes)
Adam Langley95c29f32014-06-20 12:00:00 -07001335 }
1336
Nick Harperb3d51be2016-07-01 11:43:18 -04001337 if hs.serverHello.extensions.channelIDRequested {
David Benjamin24599a82016-06-30 18:56:53 -04001338 channelIDMsg := new(channelIDMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001339 if c.config.ChannelID.Curve != elliptic.P256() {
1340 return fmt.Errorf("tls: Channel ID is not on P-256.")
1341 }
1342 var resumeHash []byte
1343 if isResume {
1344 resumeHash = hs.session.handshakeHash
1345 }
1346 r, s, err := ecdsa.Sign(c.config.rand(), c.config.ChannelID, hs.finishedHash.hashForChannelID(resumeHash))
1347 if err != nil {
1348 return err
1349 }
1350 channelID := make([]byte, 128)
1351 writeIntPadded(channelID[0:32], c.config.ChannelID.X)
1352 writeIntPadded(channelID[32:64], c.config.ChannelID.Y)
1353 writeIntPadded(channelID[64:96], r)
1354 writeIntPadded(channelID[96:128], s)
David Benjamin196df5b2016-09-21 16:23:27 -04001355 if c.config.Bugs.InvalidChannelIDSignature {
1356 channelID[64] ^= 1
1357 }
David Benjamin24599a82016-06-30 18:56:53 -04001358 channelIDMsg.channelID = channelID
David Benjamind30a9902014-08-24 01:44:23 -04001359
1360 c.channelID = &c.config.ChannelID.PublicKey
1361
David Benjamin24599a82016-06-30 18:56:53 -04001362 channelIDMsgBytes := channelIDMsg.marshal()
1363 hs.writeHash(channelIDMsgBytes, seqno)
David Benjamind30a9902014-08-24 01:44:23 -04001364 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001365 postCCSMsgs = append(postCCSMsgs, channelIDMsgBytes)
David Benjamind30a9902014-08-24 01:44:23 -04001366 }
1367
Adam Langley95c29f32014-06-20 12:00:00 -07001368 finished := new(finishedMsg)
David Benjaminf3ec83d2014-07-21 22:42:34 -04001369 if c.config.Bugs.EarlyChangeCipherSpec == 2 {
1370 finished.verifyData = hs.finishedHash.clientSum(nil)
1371 } else {
1372 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
1373 }
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001374 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001375 if c.config.Bugs.BadFinished {
1376 finished.verifyData[0]++
1377 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001378 c.clientVerify = append(c.clientVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001379 hs.finishedBytes = finished.marshal()
1380 hs.writeHash(hs.finishedBytes, seqno)
David Benjamin0b8d5da2016-07-15 00:39:56 -04001381 postCCSMsgs = append(postCCSMsgs, hs.finishedBytes)
David Benjamin86271ee2014-07-21 16:14:03 -04001382
1383 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001384 c.writeRecord(recordTypeHandshake, postCCSMsgs[0][:5])
1385 postCCSMsgs[0] = postCCSMsgs[0][5:]
David Benjamin61672812016-07-14 23:10:43 -04001386 } else if c.config.Bugs.SendUnencryptedFinished {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001387 c.writeRecord(recordTypeHandshake, postCCSMsgs[0])
1388 postCCSMsgs = postCCSMsgs[1:]
David Benjamin86271ee2014-07-21 16:14:03 -04001389 }
David Benjamin582ba042016-07-07 12:33:25 -07001390 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001391
1392 if !c.config.Bugs.SkipChangeCipherSpec &&
1393 c.config.Bugs.EarlyChangeCipherSpec == 0 {
David Benjamin8411b242015-11-26 12:07:28 -05001394 ccs := []byte{1}
1395 if c.config.Bugs.BadChangeCipherSpec != nil {
1396 ccs = c.config.Bugs.BadChangeCipherSpec
1397 }
1398 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamin86271ee2014-07-21 16:14:03 -04001399 }
1400
David Benjamin4189bd92015-01-25 23:52:39 -05001401 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1402 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1403 }
David Benjamindc3da932015-03-12 15:09:02 -04001404 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1405 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1406 return errors.New("tls: simulating post-CCS alert")
1407 }
David Benjamin4189bd92015-01-25 23:52:39 -05001408
David Benjamin0b8d5da2016-07-15 00:39:56 -04001409 if !c.config.Bugs.SkipFinished {
1410 for _, msg := range postCCSMsgs {
1411 c.writeRecord(recordTypeHandshake, msg)
1412 }
David Benjamin02edcd02016-07-27 17:40:37 -04001413
1414 if c.config.Bugs.SendExtraFinished {
1415 c.writeRecord(recordTypeHandshake, finished.marshal())
1416 }
1417
David Benjamin582ba042016-07-07 12:33:25 -07001418 c.flushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -05001419 }
Adam Langley95c29f32014-06-20 12:00:00 -07001420 return nil
1421}
1422
David Benjamin83c0bc92014-08-04 01:23:53 -04001423func (hs *clientHandshakeState) writeClientHash(msg []byte) {
1424 // writeClientHash is called before writeRecord.
1425 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1426}
1427
1428func (hs *clientHandshakeState) writeServerHash(msg []byte) {
1429 // writeServerHash is called after readHandshake.
1430 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1431}
1432
1433func (hs *clientHandshakeState) writeHash(msg []byte, seqno uint16) {
1434 if hs.c.isDTLS {
1435 // This is somewhat hacky. DTLS hashes a slightly different format.
1436 // First, the TLS header.
1437 hs.finishedHash.Write(msg[:4])
1438 // Then the sequence number and reassembled fragment offset (always 0).
1439 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1440 // Then the reassembled fragment (always equal to the message length).
1441 hs.finishedHash.Write(msg[1:4])
1442 // And then the message body.
1443 hs.finishedHash.Write(msg[4:])
1444 } else {
1445 hs.finishedHash.Write(msg)
1446 }
1447}
1448
David Benjamina6f82632016-07-01 18:44:02 -04001449// selectClientCertificate selects a certificate for use with the given
1450// certificate, or none if none match. It may return a particular certificate or
1451// nil on success, or an error on internal error.
1452func selectClientCertificate(c *Conn, certReq *certificateRequestMsg) (*Certificate, error) {
1453 // RFC 4346 on the certificateAuthorities field:
1454 // A list of the distinguished names of acceptable certificate
1455 // authorities. These distinguished names may specify a desired
1456 // distinguished name for a root CA or for a subordinate CA; thus, this
1457 // message can be used to describe both known roots and a desired
1458 // authorization space. If the certificate_authorities list is empty
1459 // then the client MAY send any certificate of the appropriate
1460 // ClientCertificateType, unless there is some external arrangement to
1461 // the contrary.
1462
1463 var rsaAvail, ecdsaAvail bool
Nick Harperb41d2e42016-07-01 17:50:32 -04001464 if !certReq.hasRequestContext {
1465 for _, certType := range certReq.certificateTypes {
1466 switch certType {
1467 case CertTypeRSASign:
1468 rsaAvail = true
1469 case CertTypeECDSASign:
1470 ecdsaAvail = true
1471 }
David Benjamina6f82632016-07-01 18:44:02 -04001472 }
1473 }
1474
1475 // We need to search our list of client certs for one
1476 // where SignatureAlgorithm is RSA and the Issuer is in
1477 // certReq.certificateAuthorities
1478findCert:
1479 for i, chain := range c.config.Certificates {
Nick Harperb41d2e42016-07-01 17:50:32 -04001480 if !certReq.hasRequestContext && !rsaAvail && !ecdsaAvail {
David Benjamina6f82632016-07-01 18:44:02 -04001481 continue
1482 }
1483
1484 // Ensure the private key supports one of the advertised
1485 // signature algorithms.
1486 if certReq.hasSignatureAlgorithm {
David Benjamin0a8deb22016-07-09 21:02:01 -07001487 if _, err := selectSignatureAlgorithm(c.vers, chain.PrivateKey, c.config, certReq.signatureAlgorithms); err != nil {
David Benjamina6f82632016-07-01 18:44:02 -04001488 continue
1489 }
1490 }
1491
1492 for j, cert := range chain.Certificate {
1493 x509Cert := chain.Leaf
1494 // parse the certificate if this isn't the leaf
1495 // node, or if chain.Leaf was nil
1496 if j != 0 || x509Cert == nil {
1497 var err error
1498 if x509Cert, err = x509.ParseCertificate(cert); err != nil {
1499 c.sendAlert(alertInternalError)
1500 return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
1501 }
1502 }
1503
Nick Harperb41d2e42016-07-01 17:50:32 -04001504 if !certReq.hasRequestContext {
1505 switch {
1506 case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
1507 case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
1508 default:
1509 continue findCert
1510 }
David Benjamina6f82632016-07-01 18:44:02 -04001511 }
1512
1513 if len(certReq.certificateAuthorities) == 0 {
1514 // They gave us an empty list, so just take the
1515 // first certificate of valid type from
1516 // c.config.Certificates.
1517 return &chain, nil
1518 }
1519
1520 for _, ca := range certReq.certificateAuthorities {
1521 if bytes.Equal(x509Cert.RawIssuer, ca) {
1522 return &chain, nil
1523 }
1524 }
1525 }
1526 }
1527
1528 return nil, nil
1529}
1530
Adam Langley95c29f32014-06-20 12:00:00 -07001531// clientSessionCacheKey returns a key used to cache sessionTickets that could
1532// be used to resume previously negotiated TLS sessions with a server.
1533func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
1534 if len(config.ServerName) > 0 {
1535 return config.ServerName
1536 }
1537 return serverAddr.String()
1538}
1539
David Benjaminfa055a22014-09-15 16:51:51 -04001540// mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
1541// given list of possible protocols and a list of the preference order. The
1542// first list must not be empty. It returns the resulting protocol and flag
Adam Langley95c29f32014-06-20 12:00:00 -07001543// indicating if the fallback case was reached.
David Benjaminfa055a22014-09-15 16:51:51 -04001544func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
1545 for _, s := range preferenceProtos {
1546 for _, c := range protos {
Adam Langley95c29f32014-06-20 12:00:00 -07001547 if s == c {
1548 return s, false
1549 }
1550 }
1551 }
1552
David Benjaminfa055a22014-09-15 16:51:51 -04001553 return protos[0], true
Adam Langley95c29f32014-06-20 12:00:00 -07001554}
David Benjamind30a9902014-08-24 01:44:23 -04001555
1556// writeIntPadded writes x into b, padded up with leading zeros as
1557// needed.
1558func writeIntPadded(b []byte, x *big.Int) {
1559 for i := range b {
1560 b[i] = 0
1561 }
1562 xb := x.Bytes()
1563 copy(b[len(b)-len(xb):], xb)
1564}