blob: 7fa7ea21f05036a974018e8820574d37520164af [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
Steven Valdezfdd10992016-09-15 16:27:05 -040060 minVersion := c.config.minVersion(c.isDTLS)
David Benjamin3c6a1ea2016-09-26 18:30:05 -040061 maxVersion := c.config.maxVersion(c.isDTLS)
Adam Langley95c29f32014-06-20 12:00:00 -070062 hello := &clientHelloMsg{
David Benjaminca6c8262014-11-15 19:06:08 -050063 isDTLS: c.isDTLS,
David Benjamin3c6a1ea2016-09-26 18:30:05 -040064 vers: versionToWire(maxVersion, c.isDTLS),
David Benjaminca6c8262014-11-15 19:06:08 -050065 compressionMethods: []uint8{compressionNone},
66 random: make([]byte, 32),
David Benjamin53210cb2016-11-16 09:01:48 +090067 ocspStapling: !c.config.Bugs.NoOCSPStapling,
68 sctListSupported: !c.config.Bugs.NoSignedCertificateTimestamps,
David Benjaminca6c8262014-11-15 19:06:08 -050069 serverName: c.config.ServerName,
70 supportedCurves: c.config.curvePreferences(),
Steven Valdeza833c352016-11-01 13:39:36 -040071 pskKEModes: []byte{pskDHEKEMode},
David Benjaminca6c8262014-11-15 19:06:08 -050072 supportedPoints: []uint8{pointFormatUncompressed},
73 nextProtoNeg: len(c.config.NextProtos) > 0,
74 secureRenegotiation: []byte{},
75 alpnProtocols: c.config.NextProtos,
76 duplicateExtension: c.config.Bugs.DuplicateExtension,
77 channelIDSupported: c.config.ChannelID != nil,
Steven Valdeza833c352016-11-01 13:39:36 -040078 npnAfterAlpn: c.config.Bugs.SwapNPNAndALPN,
Steven Valdezfdd10992016-09-15 16:27:05 -040079 extendedMasterSecret: maxVersion >= VersionTLS10,
David Benjaminca6c8262014-11-15 19:06:08 -050080 srtpProtectionProfiles: c.config.SRTPProtectionProfiles,
81 srtpMasterKeyIdentifier: c.config.Bugs.SRTPMasterKeyIdentifer,
Adam Langley09505632015-07-30 18:10:13 -070082 customExtension: c.config.Bugs.CustomExtension,
Steven Valdeza833c352016-11-01 13:39:36 -040083 pskBinderFirst: c.config.Bugs.PSKBinderFirst,
Adam Langley95c29f32014-06-20 12:00:00 -070084 }
85
David Benjamin163c9562016-08-29 23:14:17 -040086 disableEMS := c.config.Bugs.NoExtendedMasterSecret
87 if c.cipherSuite != nil {
88 disableEMS = c.config.Bugs.NoExtendedMasterSecretOnRenegotiation
89 }
90
91 if disableEMS {
Adam Langley75712922014-10-10 16:23:43 -070092 hello.extendedMasterSecret = false
93 }
94
David Benjamin55a43642015-04-20 14:45:55 -040095 if c.config.Bugs.NoSupportedCurves {
96 hello.supportedCurves = nil
97 }
98
Steven Valdeza833c352016-11-01 13:39:36 -040099 if len(c.config.Bugs.SendPSKKeyExchangeModes) != 0 {
100 hello.pskKEModes = c.config.Bugs.SendPSKKeyExchangeModes
101 }
102
David Benjaminc241d792016-09-09 10:34:20 -0400103 if c.config.Bugs.SendCompressionMethods != nil {
104 hello.compressionMethods = c.config.Bugs.SendCompressionMethods
105 }
106
Adam Langley2ae77d22014-10-28 17:29:33 -0700107 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
108 if c.config.Bugs.BadRenegotiationInfo {
109 hello.secureRenegotiation = append(hello.secureRenegotiation, c.clientVerify...)
110 hello.secureRenegotiation[0] ^= 0x80
111 } else {
112 hello.secureRenegotiation = c.clientVerify
113 }
114 }
115
David Benjamin3e052de2015-11-25 20:10:31 -0500116 if c.noRenegotiationInfo() {
David Benjaminca6554b2014-11-08 12:31:52 -0500117 hello.secureRenegotiation = nil
118 }
119
Nick Harperb41d2e42016-07-01 17:50:32 -0400120 var keyShares map[CurveID]ecdhCurve
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400121 if maxVersion >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -0400122 keyShares = make(map[CurveID]ecdhCurve)
Nick Harperdcfbc672016-07-16 17:47:31 +0200123 hello.hasKeyShares = true
David Benjamin7e1f9842016-09-20 19:24:40 -0400124 hello.trailingKeyShareData = c.config.Bugs.TrailingKeyShareData
Nick Harperdcfbc672016-07-16 17:47:31 +0200125 curvesToSend := c.config.defaultCurves()
Nick Harperb41d2e42016-07-01 17:50:32 -0400126 for _, curveID := range hello.supportedCurves {
Nick Harperdcfbc672016-07-16 17:47:31 +0200127 if !curvesToSend[curveID] {
128 continue
129 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400130 curve, ok := curveForCurveID(curveID)
131 if !ok {
132 continue
133 }
134 publicKey, err := curve.offer(c.config.rand())
135 if err != nil {
136 return err
137 }
Steven Valdez0ee2e112016-07-15 06:51:15 -0400138
139 if c.config.Bugs.SendCurve != 0 {
140 curveID = c.config.Bugs.SendCurve
141 }
142 if c.config.Bugs.InvalidECDHPoint {
143 publicKey[0] ^= 0xff
144 }
145
Nick Harperb41d2e42016-07-01 17:50:32 -0400146 hello.keyShares = append(hello.keyShares, keyShareEntry{
147 group: curveID,
148 keyExchange: publicKey,
149 })
150 keyShares[curveID] = curve
Steven Valdez143e8b32016-07-11 13:19:03 -0400151
152 if c.config.Bugs.DuplicateKeyShares {
153 hello.keyShares = append(hello.keyShares, hello.keyShares[len(hello.keyShares)-1])
154 }
155 }
156
157 if c.config.Bugs.MissingKeyShare {
Steven Valdez5440fe02016-07-18 12:40:30 -0400158 hello.hasKeyShares = false
Nick Harperb41d2e42016-07-01 17:50:32 -0400159 }
160 }
161
Adam Langley95c29f32014-06-20 12:00:00 -0700162 possibleCipherSuites := c.config.cipherSuites()
163 hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
164
165NextCipherSuite:
166 for _, suiteId := range possibleCipherSuites {
167 for _, suite := range cipherSuites {
168 if suite.id != suiteId {
169 continue
170 }
David Benjamin5ecb88b2016-10-04 17:51:35 -0400171 // Don't advertise TLS 1.2-only cipher suites unless
172 // we're attempting TLS 1.2.
173 if maxVersion < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
174 continue
175 }
176 // Don't advertise non-DTLS cipher suites in DTLS.
177 if c.isDTLS && suite.flags&suiteNoDTLS != 0 {
178 continue
David Benjamin83c0bc92014-08-04 01:23:53 -0400179 }
Adam Langley95c29f32014-06-20 12:00:00 -0700180 hello.cipherSuites = append(hello.cipherSuites, suiteId)
181 continue NextCipherSuite
182 }
183 }
184
David Benjamin5ecb88b2016-10-04 17:51:35 -0400185 if c.config.Bugs.AdvertiseAllConfiguredCiphers {
186 hello.cipherSuites = possibleCipherSuites
187 }
188
Adam Langley5021b222015-06-12 18:27:58 -0700189 if c.config.Bugs.SendRenegotiationSCSV {
190 hello.cipherSuites = append(hello.cipherSuites, renegotiationSCSV)
191 }
192
David Benjaminbef270a2014-08-02 04:22:02 -0400193 if c.config.Bugs.SendFallbackSCSV {
194 hello.cipherSuites = append(hello.cipherSuites, fallbackSCSV)
195 }
196
Adam Langley95c29f32014-06-20 12:00:00 -0700197 _, err := io.ReadFull(c.config.rand(), hello.random)
198 if err != nil {
199 c.sendAlert(alertInternalError)
200 return errors.New("tls: short read from Rand: " + err.Error())
201 }
202
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400203 if maxVersion >= VersionTLS12 && !c.config.Bugs.NoSignatureAlgorithms {
David Benjamin7a41d372016-07-09 11:21:54 -0700204 hello.signatureAlgorithms = c.config.verifySignatureAlgorithms()
Adam Langley95c29f32014-06-20 12:00:00 -0700205 }
206
207 var session *ClientSessionState
208 var cacheKey string
209 sessionCache := c.config.ClientSessionCache
Adam Langley95c29f32014-06-20 12:00:00 -0700210
211 if sessionCache != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500212 hello.ticketSupported = !c.config.SessionTicketsDisabled
Adam Langley95c29f32014-06-20 12:00:00 -0700213
214 // Try to resume a previously negotiated TLS session, if
215 // available.
216 cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
Nick Harper0b3625b2016-07-25 16:16:28 -0700217 // TODO(nharper): Support storing more than one session
218 // ticket for TLS 1.3.
Adam Langley95c29f32014-06-20 12:00:00 -0700219 candidateSession, ok := sessionCache.Get(cacheKey)
220 if ok {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500221 ticketOk := !c.config.SessionTicketsDisabled || candidateSession.sessionTicket == nil
222
Adam Langley95c29f32014-06-20 12:00:00 -0700223 // Check that the ciphersuite/version used for the
224 // previous session are still valid.
225 cipherSuiteOk := false
David Benjamin2b02f4b2016-11-16 16:11:47 +0900226 if candidateSession.vers <= VersionTLS12 {
227 for _, id := range hello.cipherSuites {
228 if id == candidateSession.cipherSuite {
229 cipherSuiteOk = true
230 break
231 }
Adam Langley95c29f32014-06-20 12:00:00 -0700232 }
David Benjamin2b02f4b2016-11-16 16:11:47 +0900233 } else {
234 // TLS 1.3 allows the cipher to change on
235 // resumption.
236 cipherSuiteOk = true
Adam Langley95c29f32014-06-20 12:00:00 -0700237 }
238
Steven Valdezfdd10992016-09-15 16:27:05 -0400239 versOk := candidateSession.vers >= minVersion &&
240 candidateSession.vers <= maxVersion
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500241 if ticketOk && versOk && cipherSuiteOk {
Adam Langley95c29f32014-06-20 12:00:00 -0700242 session = candidateSession
243 }
244 }
245 }
246
Steven Valdeza833c352016-11-01 13:39:36 -0400247 var pskCipherSuite *cipherSuite
Nick Harper0b3625b2016-07-25 16:16:28 -0700248 if session != nil && c.config.time().Before(session.ticketExpiration) {
David Benjamind5a4ecb2016-07-18 01:17:13 +0200249 ticket := session.sessionTicket
David Benjamin4199b0d2016-11-01 13:58:25 -0400250 if c.config.Bugs.FilterTicket != nil && len(ticket) > 0 {
251 // Copy the ticket so FilterTicket may act in-place.
David Benjamind5a4ecb2016-07-18 01:17:13 +0200252 ticket = make([]byte, len(session.sessionTicket))
253 copy(ticket, session.sessionTicket)
David Benjamin4199b0d2016-11-01 13:58:25 -0400254
255 ticket, err = c.config.Bugs.FilterTicket(ticket)
256 if err != nil {
257 return err
Adam Langley38311732014-10-16 19:04:35 -0700258 }
David Benjamind5a4ecb2016-07-18 01:17:13 +0200259 }
260
David Benjamin405da482016-08-08 17:25:07 -0400261 if session.vers >= VersionTLS13 || c.config.Bugs.SendBothTickets {
Steven Valdeza833c352016-11-01 13:39:36 -0400262 pskCipherSuite = cipherSuiteFromID(session.cipherSuite)
263 if pskCipherSuite == nil {
264 return errors.New("tls: client session cache has invalid cipher suite")
265 }
Nick Harper0b3625b2016-07-25 16:16:28 -0700266 // TODO(nharper): Support sending more
267 // than one PSK identity.
Steven Valdeza833c352016-11-01 13:39:36 -0400268 ticketAge := uint32(c.config.time().Sub(session.ticketCreationTime) / time.Millisecond)
Steven Valdez5b986082016-09-01 12:29:49 -0400269 psk := pskIdentity{
Steven Valdeza833c352016-11-01 13:39:36 -0400270 ticket: ticket,
271 obfuscatedTicketAge: session.ticketAgeAdd + ticketAge,
Nick Harper0b3625b2016-07-25 16:16:28 -0700272 }
Steven Valdez5b986082016-09-01 12:29:49 -0400273 hello.pskIdentities = []pskIdentity{psk}
Steven Valdezaf3b8a92016-11-01 12:49:22 -0400274
275 if c.config.Bugs.ExtraPSKIdentity {
276 hello.pskIdentities = append(hello.pskIdentities, psk)
277 }
David Benjamin405da482016-08-08 17:25:07 -0400278 }
279
280 if session.vers < VersionTLS13 || c.config.Bugs.SendBothTickets {
281 if ticket != nil {
282 hello.sessionTicket = ticket
283 // A random session ID is used to detect when the
284 // server accepted the ticket and is resuming a session
285 // (see RFC 5077).
286 sessionIdLen := 16
287 if c.config.Bugs.OversizedSessionId {
288 sessionIdLen = 33
289 }
290 hello.sessionId = make([]byte, sessionIdLen)
291 if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
292 c.sendAlert(alertInternalError)
293 return errors.New("tls: short read from Rand: " + err.Error())
294 }
295 } else {
296 hello.sessionId = session.sessionId
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500297 }
Adam Langley95c29f32014-06-20 12:00:00 -0700298 }
299 }
300
Steven Valdezfdd10992016-09-15 16:27:05 -0400301 if maxVersion == VersionTLS13 && !c.config.Bugs.OmitSupportedVersions {
302 if hello.vers >= VersionTLS13 {
303 hello.vers = VersionTLS12
304 }
305 for version := maxVersion; version >= minVersion; version-- {
306 hello.supportedVersions = append(hello.supportedVersions, versionToWire(version, c.isDTLS))
307 }
308 }
309
310 if len(c.config.Bugs.SendSupportedVersions) > 0 {
311 hello.supportedVersions = c.config.Bugs.SendSupportedVersions
312 }
313
David Benjamineed24012016-08-13 19:26:00 -0400314 if c.config.Bugs.SendClientVersion != 0 {
315 hello.vers = c.config.Bugs.SendClientVersion
316 }
317
David Benjamin75f99142016-11-12 12:36:06 +0900318 if c.config.Bugs.SendCipherSuites != nil {
319 hello.cipherSuites = c.config.Bugs.SendCipherSuites
320 }
321
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500322 if c.config.Bugs.SendEarlyDataLength > 0 && !c.config.Bugs.OmitEarlyDataExtension {
323 hello.hasEarlyData = true
324 }
325
David Benjamind86c7672014-08-02 04:07:12 -0400326 var helloBytes []byte
327 if c.config.Bugs.SendV2ClientHello {
David Benjamin94d701b2014-11-30 13:54:41 -0500328 // Test that the peer left-pads random.
329 hello.random[0] = 0
David Benjamind86c7672014-08-02 04:07:12 -0400330 v2Hello := &v2ClientHelloMsg{
331 vers: hello.vers,
332 cipherSuites: hello.cipherSuites,
333 // No session resumption for V2ClientHello.
334 sessionId: nil,
David Benjamin94d701b2014-11-30 13:54:41 -0500335 challenge: hello.random[1:],
David Benjamind86c7672014-08-02 04:07:12 -0400336 }
337 helloBytes = v2Hello.marshal()
338 c.writeV2Record(helloBytes)
339 } else {
Steven Valdeza833c352016-11-01 13:39:36 -0400340 if len(hello.pskIdentities) > 0 {
341 generatePSKBinders(hello, pskCipherSuite, session.masterSecret, []byte{}, c.config)
342 }
David Benjamind86c7672014-08-02 04:07:12 -0400343 helloBytes = hello.marshal()
Steven Valdeza833c352016-11-01 13:39:36 -0400344
David Benjamin7964b182016-07-14 23:36:30 -0400345 if c.config.Bugs.PartialClientFinishedWithClientHello {
346 // Include one byte of Finished. We can compute it
347 // without completing the handshake. This assumes we
348 // negotiate TLS 1.3 with no HelloRetryRequest or
349 // CertificateRequest.
350 toWrite := make([]byte, 0, len(helloBytes)+1)
351 toWrite = append(toWrite, helloBytes...)
352 toWrite = append(toWrite, typeFinished)
353 c.writeRecord(recordTypeHandshake, toWrite)
354 } else {
355 c.writeRecord(recordTypeHandshake, helloBytes)
356 }
David Benjamind86c7672014-08-02 04:07:12 -0400357 }
David Benjamin582ba042016-07-07 12:33:25 -0700358 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700359
David Benjamin83f90402015-01-27 01:09:43 -0500360 if err := c.simulatePacketLoss(nil); err != nil {
361 return err
362 }
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500363 if c.config.Bugs.SendEarlyAlert {
364 c.sendAlert(alertHandshakeFailure)
365 }
366 if c.config.Bugs.SendEarlyDataLength > 0 {
367 c.sendFakeEarlyData(c.config.Bugs.SendEarlyDataLength)
368 }
Adam Langley95c29f32014-06-20 12:00:00 -0700369 msg, err := c.readHandshake()
370 if err != nil {
371 return err
372 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400373
374 if c.isDTLS {
375 helloVerifyRequest, ok := msg.(*helloVerifyRequestMsg)
376 if ok {
David Benjaminda4789e2016-10-31 19:23:34 -0400377 if helloVerifyRequest.vers != versionToWire(VersionTLS10, c.isDTLS) {
David Benjamin8bc38f52014-08-16 12:07:27 -0400378 // Per RFC 6347, the version field in
379 // HelloVerifyRequest SHOULD be always DTLS
380 // 1.0. Enforce this for testing purposes.
381 return errors.New("dtls: bad HelloVerifyRequest version")
382 }
383
David Benjamin83c0bc92014-08-04 01:23:53 -0400384 hello.raw = nil
385 hello.cookie = helloVerifyRequest.cookie
386 helloBytes = hello.marshal()
387 c.writeRecord(recordTypeHandshake, helloBytes)
David Benjamin582ba042016-07-07 12:33:25 -0700388 c.flushHandshake()
David Benjamin83c0bc92014-08-04 01:23:53 -0400389
David Benjamin83f90402015-01-27 01:09:43 -0500390 if err := c.simulatePacketLoss(nil); err != nil {
391 return err
392 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400393 msg, err = c.readHandshake()
394 if err != nil {
395 return err
396 }
397 }
398 }
399
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400400 var serverWireVersion uint16
Nick Harperdcfbc672016-07-16 17:47:31 +0200401 switch m := msg.(type) {
402 case *helloRetryRequestMsg:
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400403 serverWireVersion = m.vers
Nick Harperdcfbc672016-07-16 17:47:31 +0200404 case *serverHelloMsg:
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400405 serverWireVersion = m.vers
Nick Harperdcfbc672016-07-16 17:47:31 +0200406 default:
407 c.sendAlert(alertUnexpectedMessage)
408 return fmt.Errorf("tls: received unexpected message of type %T when waiting for HelloRetryRequest or ServerHello", msg)
409 }
410
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400411 serverVersion, ok := wireToVersion(serverWireVersion, c.isDTLS)
412 if ok {
Steven Valdezfdd10992016-09-15 16:27:05 -0400413 ok = c.config.isSupportedVersion(serverVersion, c.isDTLS)
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400414 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200415 if !ok {
416 c.sendAlert(alertProtocolVersion)
417 return fmt.Errorf("tls: server selected unsupported protocol version %x", c.vers)
418 }
Steven Valdezfdd10992016-09-15 16:27:05 -0400419 c.vers = serverVersion
Nick Harperdcfbc672016-07-16 17:47:31 +0200420 c.haveVers = true
421
422 helloRetryRequest, haveHelloRetryRequest := msg.(*helloRetryRequestMsg)
423 var secondHelloBytes []byte
424 if haveHelloRetryRequest {
David Benjamin3baa6e12016-10-07 21:10:38 -0400425 if len(helloRetryRequest.cookie) > 0 {
426 hello.tls13Cookie = helloRetryRequest.cookie
427 }
428
Steven Valdez5440fe02016-07-18 12:40:30 -0400429 if c.config.Bugs.MisinterpretHelloRetryRequestCurve != 0 {
David Benjamin3baa6e12016-10-07 21:10:38 -0400430 helloRetryRequest.hasSelectedGroup = true
Steven Valdez5440fe02016-07-18 12:40:30 -0400431 helloRetryRequest.selectedGroup = c.config.Bugs.MisinterpretHelloRetryRequestCurve
432 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400433 if helloRetryRequest.hasSelectedGroup {
434 var hrrCurveFound bool
435 group := helloRetryRequest.selectedGroup
436 for _, curveID := range hello.supportedCurves {
437 if group == curveID {
438 hrrCurveFound = true
439 break
440 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200441 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400442 if !hrrCurveFound || keyShares[group] != nil {
443 c.sendAlert(alertHandshakeFailure)
444 return errors.New("tls: received invalid HelloRetryRequest")
445 }
446 curve, ok := curveForCurveID(group)
447 if !ok {
448 return errors.New("tls: Unable to get curve requested in HelloRetryRequest")
449 }
450 publicKey, err := curve.offer(c.config.rand())
451 if err != nil {
452 return err
453 }
454 keyShares[group] = curve
Steven Valdeza833c352016-11-01 13:39:36 -0400455 hello.keyShares = []keyShareEntry{{
David Benjamin3baa6e12016-10-07 21:10:38 -0400456 group: group,
457 keyExchange: publicKey,
Steven Valdeza833c352016-11-01 13:39:36 -0400458 }}
Nick Harperdcfbc672016-07-16 17:47:31 +0200459 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200460
Steven Valdez5440fe02016-07-18 12:40:30 -0400461 if c.config.Bugs.SecondClientHelloMissingKeyShare {
462 hello.hasKeyShares = false
463 }
464
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500465 hello.hasEarlyData = c.config.Bugs.SendEarlyDataOnSecondClientHello
Nick Harperdcfbc672016-07-16 17:47:31 +0200466 hello.raw = nil
467
Steven Valdeza833c352016-11-01 13:39:36 -0400468 if len(hello.pskIdentities) > 0 {
469 generatePSKBinders(hello, pskCipherSuite, session.masterSecret, append(helloBytes, helloRetryRequest.marshal()...), c.config)
470 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200471 secondHelloBytes = hello.marshal()
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500472
473 if c.config.Bugs.InterleaveEarlyData {
474 c.sendFakeEarlyData(4)
475 c.writeRecord(recordTypeHandshake, secondHelloBytes[:16])
476 c.sendFakeEarlyData(4)
477 c.writeRecord(recordTypeHandshake, secondHelloBytes[16:])
478 } else {
479 c.writeRecord(recordTypeHandshake, secondHelloBytes)
480 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200481 c.flushHandshake()
482
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500483 if c.config.Bugs.SendEarlyDataOnSecondClientHello {
484 c.sendFakeEarlyData(4)
485 }
486
Nick Harperdcfbc672016-07-16 17:47:31 +0200487 msg, err = c.readHandshake()
488 if err != nil {
489 return err
490 }
491 }
492
Adam Langley95c29f32014-06-20 12:00:00 -0700493 serverHello, ok := msg.(*serverHelloMsg)
494 if !ok {
495 c.sendAlert(alertUnexpectedMessage)
496 return unexpectedMessageError(serverHello, msg)
497 }
498
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400499 if serverWireVersion != serverHello.vers {
Adam Langley95c29f32014-06-20 12:00:00 -0700500 c.sendAlert(alertProtocolVersion)
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400501 return fmt.Errorf("tls: server sent non-matching version %x vs %x", serverWireVersion, serverHello.vers)
Adam Langley95c29f32014-06-20 12:00:00 -0700502 }
Adam Langley95c29f32014-06-20 12:00:00 -0700503
Nick Harper85f20c22016-07-04 10:11:59 -0700504 // Check for downgrade signals in the server random, per
David Benjamina128a552016-10-13 14:26:33 -0400505 // draft-ietf-tls-tls13-16, section 4.1.3.
Nick Harper85f20c22016-07-04 10:11:59 -0700506 if c.vers <= VersionTLS12 && c.config.maxVersion(c.isDTLS) >= VersionTLS13 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400507 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS13) {
Nick Harper85f20c22016-07-04 10:11:59 -0700508 c.sendAlert(alertProtocolVersion)
509 return errors.New("tls: downgrade from TLS 1.3 detected")
510 }
511 }
512 if c.vers <= VersionTLS11 && c.config.maxVersion(c.isDTLS) >= VersionTLS12 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400513 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS12) {
Nick Harper85f20c22016-07-04 10:11:59 -0700514 c.sendAlert(alertProtocolVersion)
515 return errors.New("tls: downgrade from TLS 1.2 detected")
516 }
517 }
518
Nick Harper0b3625b2016-07-25 16:16:28 -0700519 suite := mutualCipherSuite(hello.cipherSuites, serverHello.cipherSuite)
Adam Langley95c29f32014-06-20 12:00:00 -0700520 if suite == nil {
521 c.sendAlert(alertHandshakeFailure)
522 return fmt.Errorf("tls: server selected an unsupported cipher suite")
523 }
524
David Benjamin3baa6e12016-10-07 21:10:38 -0400525 if haveHelloRetryRequest && helloRetryRequest.hasSelectedGroup && helloRetryRequest.selectedGroup != serverHello.keyShare.group {
Nick Harperdcfbc672016-07-16 17:47:31 +0200526 c.sendAlert(alertHandshakeFailure)
527 return errors.New("tls: ServerHello parameters did not match HelloRetryRequest")
528 }
529
Adam Langley95c29f32014-06-20 12:00:00 -0700530 hs := &clientHandshakeState{
531 c: c,
532 serverHello: serverHello,
533 hello: hello,
534 suite: suite,
535 finishedHash: newFinishedHash(c.vers, suite),
Nick Harperb41d2e42016-07-01 17:50:32 -0400536 keyShares: keyShares,
Adam Langley95c29f32014-06-20 12:00:00 -0700537 session: session,
538 }
539
David Benjamin83c0bc92014-08-04 01:23:53 -0400540 hs.writeHash(helloBytes, hs.c.sendHandshakeSeq-1)
Nick Harperdcfbc672016-07-16 17:47:31 +0200541 if haveHelloRetryRequest {
542 hs.writeServerHash(helloRetryRequest.marshal())
543 hs.writeClientHash(secondHelloBytes)
544 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400545 hs.writeServerHash(hs.serverHello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700546
David Benjamin8d315d72016-07-18 01:03:18 +0200547 if c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -0400548 if err := hs.doTLS13Handshake(); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700549 return err
550 }
551 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400552 if c.config.Bugs.EarlyChangeCipherSpec > 0 {
553 hs.establishKeys()
554 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
555 }
556
557 if hs.serverHello.compressionMethod != compressionNone {
558 c.sendAlert(alertUnexpectedMessage)
559 return errors.New("tls: server selected unsupported compression format")
560 }
561
562 err = hs.processServerExtensions(&serverHello.extensions)
563 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700564 return err
565 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400566
567 isResume, err := hs.processServerHello()
568 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700569 return err
570 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400571
572 if isResume {
573 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
574 if err := hs.establishKeys(); err != nil {
575 return err
576 }
577 }
578 if err := hs.readSessionTicket(); err != nil {
579 return err
580 }
581 if err := hs.readFinished(c.firstFinished[:]); err != nil {
582 return err
583 }
584 if err := hs.sendFinished(nil, isResume); err != nil {
585 return err
586 }
587 } else {
588 if err := hs.doFullHandshake(); err != nil {
589 return err
590 }
591 if err := hs.establishKeys(); err != nil {
592 return err
593 }
594 if err := hs.sendFinished(c.firstFinished[:], isResume); err != nil {
595 return err
596 }
597 // Most retransmits are triggered by a timeout, but the final
598 // leg of the handshake is retransmited upon re-receiving a
599 // Finished.
600 if err := c.simulatePacketLoss(func() {
David Benjamin02edcd02016-07-27 17:40:37 -0400601 c.sendHandshakeSeq--
Nick Harperb41d2e42016-07-01 17:50:32 -0400602 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
603 c.flushHandshake()
604 }); err != nil {
605 return err
606 }
607 if err := hs.readSessionTicket(); err != nil {
608 return err
609 }
610 if err := hs.readFinished(nil); err != nil {
611 return err
612 }
Adam Langley95c29f32014-06-20 12:00:00 -0700613 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400614
615 if sessionCache != nil && hs.session != nil && session != hs.session {
616 if c.config.Bugs.RequireSessionTickets && len(hs.session.sessionTicket) == 0 {
617 return errors.New("tls: new session used session IDs instead of tickets")
618 }
619 sessionCache.Put(cacheKey, hs.session)
David Benjamin83f90402015-01-27 01:09:43 -0500620 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400621
622 c.didResume = isResume
David Benjamin97a0a082016-07-13 17:57:35 -0400623 c.exporterSecret = hs.masterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700624 }
625
Adam Langley95c29f32014-06-20 12:00:00 -0700626 c.handshakeComplete = true
David Benjaminc565ebb2015-04-03 04:06:36 -0400627 c.cipherSuite = suite
628 copy(c.clientRandom[:], hs.hello.random)
629 copy(c.serverRandom[:], hs.serverHello.random)
Paul Lietar4fac72e2015-09-09 13:44:55 +0100630
Adam Langley95c29f32014-06-20 12:00:00 -0700631 return nil
632}
633
Nick Harperb41d2e42016-07-01 17:50:32 -0400634func (hs *clientHandshakeState) doTLS13Handshake() error {
635 c := hs.c
636
637 // Once the PRF hash is known, TLS 1.3 does not require a handshake
638 // buffer.
639 hs.finishedHash.discardHandshakeBuffer()
640
641 zeroSecret := hs.finishedHash.zeroSecret()
642
643 // Resolve PSK and compute the early secret.
644 //
645 // TODO(davidben): This will need to be handled slightly earlier once
646 // 0-RTT is implemented.
Steven Valdez803c77a2016-09-06 14:13:43 -0400647 if hs.serverHello.hasPSKIdentity {
Nick Harper0b3625b2016-07-25 16:16:28 -0700648 // We send at most one PSK identity.
649 if hs.session == nil || hs.serverHello.pskIdentity != 0 {
650 c.sendAlert(alertUnknownPSKIdentity)
651 return errors.New("tls: server sent unknown PSK identity")
652 }
David Benjamin2b02f4b2016-11-16 16:11:47 +0900653 sessionCipher := cipherSuiteFromID(hs.session.cipherSuite)
654 if sessionCipher == nil || sessionCipher.hash() != hs.suite.hash() {
Nick Harper0b3625b2016-07-25 16:16:28 -0700655 c.sendAlert(alertHandshakeFailure)
David Benjamin2b02f4b2016-11-16 16:11:47 +0900656 return errors.New("tls: server resumed an invalid session for the cipher suite")
Nick Harper0b3625b2016-07-25 16:16:28 -0700657 }
David Benjamin48891ad2016-12-04 00:02:43 -0500658 hs.finishedHash.addEntropy(hs.session.masterSecret)
Nick Harper0b3625b2016-07-25 16:16:28 -0700659 c.didResume = true
Nick Harperb41d2e42016-07-01 17:50:32 -0400660 } else {
David Benjamin48891ad2016-12-04 00:02:43 -0500661 hs.finishedHash.addEntropy(zeroSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400662 }
663
Steven Valdeza833c352016-11-01 13:39:36 -0400664 if !hs.serverHello.hasKeyShare {
665 c.sendAlert(alertUnsupportedExtension)
666 return errors.New("tls: server omitted KeyShare on resumption.")
667 }
668
Nick Harperb41d2e42016-07-01 17:50:32 -0400669 // Resolve ECDHE and compute the handshake secret.
Steven Valdez803c77a2016-09-06 14:13:43 -0400670 if !c.config.Bugs.MissingKeyShare && !c.config.Bugs.SecondClientHelloMissingKeyShare {
Nick Harperb41d2e42016-07-01 17:50:32 -0400671 curve, ok := hs.keyShares[hs.serverHello.keyShare.group]
672 if !ok {
673 c.sendAlert(alertHandshakeFailure)
674 return errors.New("tls: server selected an unsupported group")
675 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400676 c.curveID = hs.serverHello.keyShare.group
Nick Harperb41d2e42016-07-01 17:50:32 -0400677
David Benjamin48891ad2016-12-04 00:02:43 -0500678 ecdheSecret, err := curve.finish(hs.serverHello.keyShare.keyExchange)
Nick Harperb41d2e42016-07-01 17:50:32 -0400679 if err != nil {
680 return err
681 }
David Benjamin48891ad2016-12-04 00:02:43 -0500682 hs.finishedHash.addEntropy(ecdheSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400683 } else {
David Benjamin48891ad2016-12-04 00:02:43 -0500684 hs.finishedHash.addEntropy(zeroSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400685 }
686
Nick Harperb41d2e42016-07-01 17:50:32 -0400687 // Switch to handshake traffic keys.
David Benjamin48891ad2016-12-04 00:02:43 -0500688 clientHandshakeTrafficSecret := hs.finishedHash.deriveSecret(clientHandshakeTrafficLabel)
Steven Valdeza833c352016-11-01 13:39:36 -0400689 c.out.useTrafficSecret(c.vers, hs.suite, clientHandshakeTrafficSecret, clientWrite)
David Benjamin48891ad2016-12-04 00:02:43 -0500690 serverHandshakeTrafficSecret := hs.finishedHash.deriveSecret(serverHandshakeTrafficLabel)
Steven Valdeza833c352016-11-01 13:39:36 -0400691 c.in.useTrafficSecret(c.vers, hs.suite, serverHandshakeTrafficSecret, serverWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -0400692
693 msg, err := c.readHandshake()
694 if err != nil {
695 return err
696 }
697
698 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
699 if !ok {
700 c.sendAlert(alertUnexpectedMessage)
701 return unexpectedMessageError(encryptedExtensions, msg)
702 }
703 hs.writeServerHash(encryptedExtensions.marshal())
704
705 err = hs.processServerExtensions(&encryptedExtensions.extensions)
706 if err != nil {
707 return err
708 }
709
710 var chainToSend *Certificate
David Benjamin8d343b42016-07-09 14:26:01 -0700711 var certReq *certificateRequestMsg
Steven Valdeza833c352016-11-01 13:39:36 -0400712 if c.didResume {
Nick Harper0b3625b2016-07-25 16:16:28 -0700713 // Copy over authentication from the session.
714 c.peerCertificates = hs.session.serverCertificates
715 c.sctList = hs.session.sctList
716 c.ocspResponse = hs.session.ocspResponse
David Benjamin44b33bc2016-07-01 22:40:23 -0400717 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400718 msg, err := c.readHandshake()
719 if err != nil {
720 return err
721 }
722
David Benjamin8d343b42016-07-09 14:26:01 -0700723 var ok bool
724 certReq, ok = msg.(*certificateRequestMsg)
Nick Harperb41d2e42016-07-01 17:50:32 -0400725 if ok {
David Benjamin8a8349b2016-08-18 02:32:23 -0400726 if len(certReq.requestContext) != 0 {
727 return errors.New("tls: non-empty certificate request context sent in handshake")
728 }
729
David Benjaminb62d2872016-07-18 14:55:02 +0200730 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
731 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
732 }
733
Nick Harperb41d2e42016-07-01 17:50:32 -0400734 hs.writeServerHash(certReq.marshal())
Nick Harperb41d2e42016-07-01 17:50:32 -0400735
736 chainToSend, err = selectClientCertificate(c, certReq)
737 if err != nil {
738 return err
739 }
740
741 msg, err = c.readHandshake()
742 if err != nil {
743 return err
744 }
745 }
746
747 certMsg, ok := msg.(*certificateMsg)
748 if !ok {
749 c.sendAlert(alertUnexpectedMessage)
750 return unexpectedMessageError(certMsg, msg)
751 }
752 hs.writeServerHash(certMsg.marshal())
753
David Benjamin53210cb2016-11-16 09:01:48 +0900754 // Check for unsolicited extensions.
755 for i, cert := range certMsg.certificates {
756 if c.config.Bugs.NoOCSPStapling && cert.ocspResponse != nil {
757 c.sendAlert(alertUnsupportedExtension)
758 return errors.New("tls: unexpected OCSP response in the server certificate")
759 }
760 if c.config.Bugs.NoSignedCertificateTimestamps && cert.sctList != nil {
761 c.sendAlert(alertUnsupportedExtension)
762 return errors.New("tls: unexpected SCT list in the server certificate")
763 }
764 if i > 0 && c.config.Bugs.ExpectNoExtensionsOnIntermediate && (cert.ocspResponse != nil || cert.sctList != nil) {
765 c.sendAlert(alertUnsupportedExtension)
766 return errors.New("tls: unexpected extensions in the server certificate")
767 }
768 }
769
Nick Harperb41d2e42016-07-01 17:50:32 -0400770 if err := hs.verifyCertificates(certMsg); err != nil {
771 return err
772 }
773 leaf := c.peerCertificates[0]
Steven Valdeza833c352016-11-01 13:39:36 -0400774 c.ocspResponse = certMsg.certificates[0].ocspResponse
775 c.sctList = certMsg.certificates[0].sctList
776
Nick Harperb41d2e42016-07-01 17:50:32 -0400777 msg, err = c.readHandshake()
778 if err != nil {
779 return err
780 }
781 certVerifyMsg, ok := msg.(*certificateVerifyMsg)
782 if !ok {
783 c.sendAlert(alertUnexpectedMessage)
784 return unexpectedMessageError(certVerifyMsg, msg)
785 }
786
David Benjaminf74ec792016-07-13 21:18:49 -0400787 c.peerSignatureAlgorithm = certVerifyMsg.signatureAlgorithm
Nick Harperb41d2e42016-07-01 17:50:32 -0400788 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
David Benjamin1fb125c2016-07-08 18:52:12 -0700789 err = verifyMessage(c.vers, leaf.PublicKey, c.config, certVerifyMsg.signatureAlgorithm, input, certVerifyMsg.signature)
Nick Harperb41d2e42016-07-01 17:50:32 -0400790 if err != nil {
791 return err
792 }
793
794 hs.writeServerHash(certVerifyMsg.marshal())
795 }
796
797 msg, err = c.readHandshake()
798 if err != nil {
799 return err
800 }
801 serverFinished, ok := msg.(*finishedMsg)
802 if !ok {
803 c.sendAlert(alertUnexpectedMessage)
804 return unexpectedMessageError(serverFinished, msg)
805 }
806
Steven Valdezc4aa7272016-10-03 12:25:56 -0400807 verify := hs.finishedHash.serverSum(serverHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400808 if len(verify) != len(serverFinished.verifyData) ||
809 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
810 c.sendAlert(alertHandshakeFailure)
811 return errors.New("tls: server's Finished message was incorrect")
812 }
813
814 hs.writeServerHash(serverFinished.marshal())
815
816 // The various secrets do not incorporate the client's final leg, so
817 // derive them now before updating the handshake context.
David Benjamin48891ad2016-12-04 00:02:43 -0500818 hs.finishedHash.addEntropy(zeroSecret)
819 clientTrafficSecret := hs.finishedHash.deriveSecret(clientApplicationTrafficLabel)
820 serverTrafficSecret := hs.finishedHash.deriveSecret(serverApplicationTrafficLabel)
Nick Harperb41d2e42016-07-01 17:50:32 -0400821
Steven Valdez0ee2e112016-07-15 06:51:15 -0400822 if certReq != nil && !c.config.Bugs.SkipClientCertificate {
David Benjamin8d343b42016-07-09 14:26:01 -0700823 certMsg := &certificateMsg{
824 hasRequestContext: true,
825 requestContext: certReq.requestContext,
826 }
827 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -0400828 for _, certData := range chainToSend.Certificate {
829 certMsg.certificates = append(certMsg.certificates, certificateEntry{
830 data: certData,
831 extraExtension: c.config.Bugs.SendExtensionOnCertificate,
832 })
833 }
David Benjamin8d343b42016-07-09 14:26:01 -0700834 }
835 hs.writeClientHash(certMsg.marshal())
836 c.writeRecord(recordTypeHandshake, certMsg.marshal())
837
838 if chainToSend != nil {
839 certVerify := &certificateVerifyMsg{
840 hasSignatureAlgorithm: true,
841 }
842
843 // Determine the hash to sign.
844 privKey := chainToSend.PrivateKey
845
846 var err error
847 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
848 if err != nil {
849 c.sendAlert(alertInternalError)
850 return err
851 }
852
853 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
854 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
855 if err != nil {
856 c.sendAlert(alertInternalError)
857 return err
858 }
Steven Valdez0ee2e112016-07-15 06:51:15 -0400859 if c.config.Bugs.SendSignatureAlgorithm != 0 {
860 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
861 }
David Benjamin8d343b42016-07-09 14:26:01 -0700862
863 hs.writeClientHash(certVerify.marshal())
864 c.writeRecord(recordTypeHandshake, certVerify.marshal())
865 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400866 }
867
Nick Harper60a85cb2016-09-23 16:25:11 -0700868 if encryptedExtensions.extensions.channelIDRequested {
869 channelIDHash := crypto.SHA256.New()
870 channelIDHash.Write(hs.finishedHash.certificateVerifyInput(channelIDContextTLS13))
871 channelIDMsgBytes, err := hs.writeChannelIDMessage(channelIDHash.Sum(nil))
872 if err != nil {
873 return err
874 }
875 hs.writeClientHash(channelIDMsgBytes)
876 c.writeRecord(recordTypeHandshake, channelIDMsgBytes)
877 }
878
Nick Harperb41d2e42016-07-01 17:50:32 -0400879 // Send a client Finished message.
880 finished := new(finishedMsg)
Steven Valdezc4aa7272016-10-03 12:25:56 -0400881 finished.verifyData = hs.finishedHash.clientSum(clientHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400882 if c.config.Bugs.BadFinished {
883 finished.verifyData[0]++
884 }
David Benjamin97a0a082016-07-13 17:57:35 -0400885 hs.writeClientHash(finished.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400886 if c.config.Bugs.PartialClientFinishedWithClientHello {
887 // The first byte has already been sent.
888 c.writeRecord(recordTypeHandshake, finished.marshal()[1:])
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500889 } else if c.config.Bugs.InterleaveEarlyData {
890 finishedBytes := finished.marshal()
891 c.sendFakeEarlyData(4)
892 c.writeRecord(recordTypeHandshake, finishedBytes[:1])
893 c.sendFakeEarlyData(4)
894 c.writeRecord(recordTypeHandshake, finishedBytes[1:])
David Benjamin7964b182016-07-14 23:36:30 -0400895 } else {
896 c.writeRecord(recordTypeHandshake, finished.marshal())
897 }
David Benjamin02edcd02016-07-27 17:40:37 -0400898 if c.config.Bugs.SendExtraFinished {
899 c.writeRecord(recordTypeHandshake, finished.marshal())
900 }
David Benjaminee51a222016-07-07 18:34:12 -0700901 c.flushHandshake()
Nick Harperb41d2e42016-07-01 17:50:32 -0400902
903 // Switch to application data keys.
Steven Valdeza833c352016-11-01 13:39:36 -0400904 c.out.useTrafficSecret(c.vers, hs.suite, clientTrafficSecret, clientWrite)
905 c.in.useTrafficSecret(c.vers, hs.suite, serverTrafficSecret, serverWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -0400906
David Benjamin48891ad2016-12-04 00:02:43 -0500907 c.exporterSecret = hs.finishedHash.deriveSecret(exporterLabel)
908 c.resumptionSecret = hs.finishedHash.deriveSecret(resumptionLabel)
Nick Harperb41d2e42016-07-01 17:50:32 -0400909 return nil
910}
911
Adam Langley95c29f32014-06-20 12:00:00 -0700912func (hs *clientHandshakeState) doFullHandshake() error {
913 c := hs.c
914
David Benjamin48cae082014-10-27 01:06:24 -0400915 var leaf *x509.Certificate
916 if hs.suite.flags&suitePSK == 0 {
917 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700918 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700919 return err
920 }
Adam Langley95c29f32014-06-20 12:00:00 -0700921
David Benjamin48cae082014-10-27 01:06:24 -0400922 certMsg, ok := msg.(*certificateMsg)
David Benjamin75051442016-07-01 18:58:51 -0400923 if !ok {
David Benjamin48cae082014-10-27 01:06:24 -0400924 c.sendAlert(alertUnexpectedMessage)
925 return unexpectedMessageError(certMsg, msg)
926 }
927 hs.writeServerHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700928
David Benjamin75051442016-07-01 18:58:51 -0400929 if err := hs.verifyCertificates(certMsg); err != nil {
930 return err
David Benjamin48cae082014-10-27 01:06:24 -0400931 }
David Benjamin75051442016-07-01 18:58:51 -0400932 leaf = c.peerCertificates[0]
David Benjamin48cae082014-10-27 01:06:24 -0400933 }
Adam Langley95c29f32014-06-20 12:00:00 -0700934
Nick Harperb3d51be2016-07-01 11:43:18 -0400935 if hs.serverHello.extensions.ocspStapling {
David Benjamin48cae082014-10-27 01:06:24 -0400936 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700937 if err != nil {
938 return err
939 }
940 cs, ok := msg.(*certificateStatusMsg)
941 if !ok {
942 c.sendAlert(alertUnexpectedMessage)
943 return unexpectedMessageError(cs, msg)
944 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400945 hs.writeServerHash(cs.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700946
947 if cs.statusType == statusTypeOCSP {
948 c.ocspResponse = cs.response
949 }
950 }
951
David Benjamin48cae082014-10-27 01:06:24 -0400952 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700953 if err != nil {
954 return err
955 }
956
957 keyAgreement := hs.suite.ka(c.vers)
958
959 skx, ok := msg.(*serverKeyExchangeMsg)
960 if ok {
David Benjamin83c0bc92014-08-04 01:23:53 -0400961 hs.writeServerHash(skx.marshal())
David Benjamin48cae082014-10-27 01:06:24 -0400962 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, leaf, skx)
Adam Langley95c29f32014-06-20 12:00:00 -0700963 if err != nil {
964 c.sendAlert(alertUnexpectedMessage)
965 return err
966 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400967 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
968 c.curveID = ecdhe.curveID
969 }
Adam Langley95c29f32014-06-20 12:00:00 -0700970
Nick Harper60edffd2016-06-21 15:19:24 -0700971 c.peerSignatureAlgorithm = keyAgreement.peerSignatureAlgorithm()
972
Adam Langley95c29f32014-06-20 12:00:00 -0700973 msg, err = c.readHandshake()
974 if err != nil {
975 return err
976 }
977 }
978
979 var chainToSend *Certificate
980 var certRequested bool
981 certReq, ok := msg.(*certificateRequestMsg)
982 if ok {
983 certRequested = true
David Benjamin7a41d372016-07-09 11:21:54 -0700984 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
985 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
986 }
Adam Langley95c29f32014-06-20 12:00:00 -0700987
David Benjamin83c0bc92014-08-04 01:23:53 -0400988 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700989
David Benjamina6f82632016-07-01 18:44:02 -0400990 chainToSend, err = selectClientCertificate(c, certReq)
991 if err != nil {
992 return err
Adam Langley95c29f32014-06-20 12:00:00 -0700993 }
994
995 msg, err = c.readHandshake()
996 if err != nil {
997 return err
998 }
999 }
1000
1001 shd, ok := msg.(*serverHelloDoneMsg)
1002 if !ok {
1003 c.sendAlert(alertUnexpectedMessage)
1004 return unexpectedMessageError(shd, msg)
1005 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001006 hs.writeServerHash(shd.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001007
1008 // If the server requested a certificate then we have to send a
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001009 // Certificate message in TLS, even if it's empty because we don't have
1010 // a certificate to send. In SSL 3.0, skip the message and send a
1011 // no_certificate warning alert.
Adam Langley95c29f32014-06-20 12:00:00 -07001012 if certRequested {
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001013 if c.vers == VersionSSL30 && chainToSend == nil {
1014 c.sendAlert(alertNoCertficate)
1015 } else if !c.config.Bugs.SkipClientCertificate {
1016 certMsg := new(certificateMsg)
1017 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -04001018 for _, certData := range chainToSend.Certificate {
1019 certMsg.certificates = append(certMsg.certificates, certificateEntry{
1020 data: certData,
1021 })
1022 }
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001023 }
1024 hs.writeClientHash(certMsg.marshal())
1025 c.writeRecord(recordTypeHandshake, certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001026 }
Adam Langley95c29f32014-06-20 12:00:00 -07001027 }
1028
David Benjamin48cae082014-10-27 01:06:24 -04001029 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, leaf)
Adam Langley95c29f32014-06-20 12:00:00 -07001030 if err != nil {
1031 c.sendAlert(alertInternalError)
1032 return err
1033 }
1034 if ckx != nil {
David Benjaminf3ec83d2014-07-21 22:42:34 -04001035 if c.config.Bugs.EarlyChangeCipherSpec < 2 {
David Benjamin83c0bc92014-08-04 01:23:53 -04001036 hs.writeClientHash(ckx.marshal())
David Benjaminf3ec83d2014-07-21 22:42:34 -04001037 }
Adam Langley95c29f32014-06-20 12:00:00 -07001038 c.writeRecord(recordTypeHandshake, ckx.marshal())
1039 }
1040
Nick Harperb3d51be2016-07-01 11:43:18 -04001041 if hs.serverHello.extensions.extendedMasterSecret && c.vers >= VersionTLS10 {
Adam Langley75712922014-10-10 16:23:43 -07001042 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1043 c.extendedMasterSecret = true
1044 } else {
1045 if c.config.Bugs.RequireExtendedMasterSecret {
1046 return errors.New("tls: extended master secret required but not supported by peer")
1047 }
1048 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
1049 }
David Benjamine098ec22014-08-27 23:13:20 -04001050
Adam Langley95c29f32014-06-20 12:00:00 -07001051 if chainToSend != nil {
Adam Langley95c29f32014-06-20 12:00:00 -07001052 certVerify := &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001053 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001054 }
1055
David Benjamin72dc7832015-03-16 17:49:43 -04001056 // Determine the hash to sign.
Nick Harper60edffd2016-06-21 15:19:24 -07001057 privKey := c.config.Certificates[0].PrivateKey
David Benjamin72dc7832015-03-16 17:49:43 -04001058
Nick Harper60edffd2016-06-21 15:19:24 -07001059 if certVerify.hasSignatureAlgorithm {
David Benjamin0a8deb22016-07-09 21:02:01 -07001060 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
Nick Harper60edffd2016-06-21 15:19:24 -07001061 if err != nil {
1062 c.sendAlert(alertInternalError)
1063 return err
Adam Langley95c29f32014-06-20 12:00:00 -07001064 }
Nick Harper60edffd2016-06-21 15:19:24 -07001065 }
1066
1067 if c.vers > VersionSSL30 {
David Benjamin5208fd42016-07-13 21:43:25 -04001068 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, hs.finishedHash.buffer)
David Benjamina95e9f32016-07-08 16:28:04 -07001069 if err == nil && c.config.Bugs.SendSignatureAlgorithm != 0 {
1070 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
1071 }
Nick Harper60edffd2016-06-21 15:19:24 -07001072 } else {
1073 // SSL 3.0's client certificate construction is
1074 // incompatible with signatureAlgorithm.
1075 rsaKey, ok := privKey.(*rsa.PrivateKey)
1076 if !ok {
1077 err = errors.New("unsupported signature type for client certificate")
1078 } else {
1079 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
David Benjamin5208fd42016-07-13 21:43:25 -04001080 if c.config.Bugs.InvalidSignature {
Nick Harper60edffd2016-06-21 15:19:24 -07001081 digest[0] ^= 0x80
1082 }
1083 certVerify.signature, err = rsa.SignPKCS1v15(c.config.rand(), rsaKey, crypto.MD5SHA1, digest)
1084 }
Adam Langley95c29f32014-06-20 12:00:00 -07001085 }
1086 if err != nil {
1087 c.sendAlert(alertInternalError)
1088 return errors.New("tls: failed to sign handshake with client certificate: " + err.Error())
1089 }
Adam Langley95c29f32014-06-20 12:00:00 -07001090
David Benjamin83c0bc92014-08-04 01:23:53 -04001091 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001092 c.writeRecord(recordTypeHandshake, certVerify.marshal())
1093 }
David Benjamin82261be2016-07-07 14:32:50 -07001094 // flushHandshake will be called in sendFinished.
Adam Langley95c29f32014-06-20 12:00:00 -07001095
David Benjamine098ec22014-08-27 23:13:20 -04001096 hs.finishedHash.discardHandshakeBuffer()
1097
Adam Langley95c29f32014-06-20 12:00:00 -07001098 return nil
1099}
1100
David Benjamin75051442016-07-01 18:58:51 -04001101func (hs *clientHandshakeState) verifyCertificates(certMsg *certificateMsg) error {
1102 c := hs.c
1103
1104 if len(certMsg.certificates) == 0 {
1105 c.sendAlert(alertIllegalParameter)
1106 return errors.New("tls: no certificates sent")
1107 }
1108
1109 certs := make([]*x509.Certificate, len(certMsg.certificates))
Steven Valdeza833c352016-11-01 13:39:36 -04001110 for i, certEntry := range certMsg.certificates {
1111 cert, err := x509.ParseCertificate(certEntry.data)
David Benjamin75051442016-07-01 18:58:51 -04001112 if err != nil {
1113 c.sendAlert(alertBadCertificate)
1114 return errors.New("tls: failed to parse certificate from server: " + err.Error())
1115 }
1116 certs[i] = cert
1117 }
1118
1119 if !c.config.InsecureSkipVerify {
1120 opts := x509.VerifyOptions{
1121 Roots: c.config.RootCAs,
1122 CurrentTime: c.config.time(),
1123 DNSName: c.config.ServerName,
1124 Intermediates: x509.NewCertPool(),
1125 }
1126
1127 for i, cert := range certs {
1128 if i == 0 {
1129 continue
1130 }
1131 opts.Intermediates.AddCert(cert)
1132 }
1133 var err error
1134 c.verifiedChains, err = certs[0].Verify(opts)
1135 if err != nil {
1136 c.sendAlert(alertBadCertificate)
1137 return err
1138 }
1139 }
1140
1141 switch certs[0].PublicKey.(type) {
1142 case *rsa.PublicKey, *ecdsa.PublicKey:
1143 break
1144 default:
1145 c.sendAlert(alertUnsupportedCertificate)
1146 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
1147 }
1148
1149 c.peerCertificates = certs
1150 return nil
1151}
1152
Adam Langley95c29f32014-06-20 12:00:00 -07001153func (hs *clientHandshakeState) establishKeys() error {
1154 c := hs.c
1155
1156 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001157 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 -07001158 var clientCipher, serverCipher interface{}
1159 var clientHash, serverHash macFunction
1160 if hs.suite.cipher != nil {
1161 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
1162 clientHash = hs.suite.mac(c.vers, clientMAC)
1163 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
1164 serverHash = hs.suite.mac(c.vers, serverMAC)
1165 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001166 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1167 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001168 }
1169
1170 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
1171 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
1172 return nil
1173}
1174
David Benjamin75101402016-07-01 13:40:23 -04001175func (hs *clientHandshakeState) processServerExtensions(serverExtensions *serverExtensions) error {
1176 c := hs.c
1177
David Benjamin8d315d72016-07-18 01:03:18 +02001178 if c.vers < VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001179 if c.config.Bugs.RequireRenegotiationInfo && serverExtensions.secureRenegotiation == nil {
1180 return errors.New("tls: renegotiation extension missing")
1181 }
David Benjamin75101402016-07-01 13:40:23 -04001182
Nick Harperb41d2e42016-07-01 17:50:32 -04001183 if len(c.clientVerify) > 0 && !c.noRenegotiationInfo() {
1184 var expectedRenegInfo []byte
1185 expectedRenegInfo = append(expectedRenegInfo, c.clientVerify...)
1186 expectedRenegInfo = append(expectedRenegInfo, c.serverVerify...)
1187 if !bytes.Equal(serverExtensions.secureRenegotiation, expectedRenegInfo) {
1188 c.sendAlert(alertHandshakeFailure)
1189 return fmt.Errorf("tls: renegotiation mismatch")
1190 }
David Benjamin75101402016-07-01 13:40:23 -04001191 }
David Benjamincea0ab42016-07-14 12:33:14 -04001192 } else if serverExtensions.secureRenegotiation != nil {
1193 return errors.New("tls: renegotiation info sent in TLS 1.3")
David Benjamin75101402016-07-01 13:40:23 -04001194 }
1195
1196 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
1197 if serverExtensions.customExtension != *expected {
1198 return fmt.Errorf("tls: bad custom extension contents %q", serverExtensions.customExtension)
1199 }
1200 }
1201
1202 clientDidNPN := hs.hello.nextProtoNeg
1203 clientDidALPN := len(hs.hello.alpnProtocols) > 0
1204 serverHasNPN := serverExtensions.nextProtoNeg
1205 serverHasALPN := len(serverExtensions.alpnProtocol) > 0
1206
1207 if !clientDidNPN && serverHasNPN {
1208 c.sendAlert(alertHandshakeFailure)
1209 return errors.New("server advertised unrequested NPN extension")
1210 }
1211
1212 if !clientDidALPN && serverHasALPN {
1213 c.sendAlert(alertHandshakeFailure)
1214 return errors.New("server advertised unrequested ALPN extension")
1215 }
1216
1217 if serverHasNPN && serverHasALPN {
1218 c.sendAlert(alertHandshakeFailure)
1219 return errors.New("server advertised both NPN and ALPN extensions")
1220 }
1221
1222 if serverHasALPN {
1223 c.clientProtocol = serverExtensions.alpnProtocol
1224 c.clientProtocolFallback = false
1225 c.usedALPN = true
1226 }
1227
David Benjamin8d315d72016-07-18 01:03:18 +02001228 if serverHasNPN && c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001229 c.sendAlert(alertHandshakeFailure)
1230 return errors.New("server advertised NPN over TLS 1.3")
1231 }
1232
David Benjamin75101402016-07-01 13:40:23 -04001233 if !hs.hello.channelIDSupported && serverExtensions.channelIDRequested {
1234 c.sendAlert(alertHandshakeFailure)
1235 return errors.New("server advertised unrequested Channel ID extension")
1236 }
1237
David Benjamin8d315d72016-07-18 01:03:18 +02001238 if serverExtensions.extendedMasterSecret && c.vers >= VersionTLS13 {
David Benjamine9077652016-07-13 21:02:08 -04001239 return errors.New("tls: server advertised extended master secret over TLS 1.3")
1240 }
1241
David Benjamin8d315d72016-07-18 01:03:18 +02001242 if serverExtensions.ticketSupported && c.vers >= VersionTLS13 {
Steven Valdez143e8b32016-07-11 13:19:03 -04001243 return errors.New("tls: server advertised ticket extension over TLS 1.3")
1244 }
1245
Steven Valdeza833c352016-11-01 13:39:36 -04001246 if serverExtensions.ocspStapling && c.vers >= VersionTLS13 {
1247 return errors.New("tls: server advertised OCSP in ServerHello over TLS 1.3")
1248 }
1249
David Benjamin53210cb2016-11-16 09:01:48 +09001250 if serverExtensions.ocspStapling && c.config.Bugs.NoOCSPStapling {
1251 return errors.New("tls: server advertised unrequested OCSP extension")
1252 }
1253
Steven Valdeza833c352016-11-01 13:39:36 -04001254 if len(serverExtensions.sctList) > 0 && c.vers >= VersionTLS13 {
1255 return errors.New("tls: server advertised SCTs in ServerHello over TLS 1.3")
1256 }
1257
David Benjamin53210cb2016-11-16 09:01:48 +09001258 if len(serverExtensions.sctList) > 0 && c.config.Bugs.NoSignedCertificateTimestamps {
1259 return errors.New("tls: server advertised unrequested SCTs")
1260 }
1261
David Benjamin75101402016-07-01 13:40:23 -04001262 if serverExtensions.srtpProtectionProfile != 0 {
1263 if serverExtensions.srtpMasterKeyIdentifier != "" {
1264 return errors.New("tls: server selected SRTP MKI value")
1265 }
1266
1267 found := false
1268 for _, p := range c.config.SRTPProtectionProfiles {
1269 if p == serverExtensions.srtpProtectionProfile {
1270 found = true
1271 break
1272 }
1273 }
1274 if !found {
1275 return errors.New("tls: server advertised unsupported SRTP profile")
1276 }
1277
1278 c.srtpProtectionProfile = serverExtensions.srtpProtectionProfile
1279 }
1280
1281 return nil
1282}
1283
Adam Langley95c29f32014-06-20 12:00:00 -07001284func (hs *clientHandshakeState) serverResumedSession() bool {
1285 // If the server responded with the same sessionId then it means the
1286 // sessionTicket is being used to resume a TLS session.
1287 return hs.session != nil && hs.hello.sessionId != nil &&
1288 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
1289}
1290
1291func (hs *clientHandshakeState) processServerHello() (bool, error) {
1292 c := hs.c
1293
Adam Langley95c29f32014-06-20 12:00:00 -07001294 if hs.serverResumedSession() {
David Benjamin4b27d9f2015-05-12 22:42:52 -04001295 // For test purposes, assert that the server never accepts the
1296 // resumption offer on renegotiation.
1297 if c.cipherSuite != nil && c.config.Bugs.FailIfResumeOnRenego {
1298 return false, errors.New("tls: server resumed session on renegotiation")
1299 }
1300
Nick Harperb3d51be2016-07-01 11:43:18 -04001301 if hs.serverHello.extensions.sctList != nil {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001302 return false, errors.New("tls: server sent SCT extension on session resumption")
1303 }
1304
Nick Harperb3d51be2016-07-01 11:43:18 -04001305 if hs.serverHello.extensions.ocspStapling {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001306 return false, errors.New("tls: server sent OCSP extension on session resumption")
1307 }
1308
Adam Langley95c29f32014-06-20 12:00:00 -07001309 // Restore masterSecret and peerCerts from previous state
1310 hs.masterSecret = hs.session.masterSecret
1311 c.peerCertificates = hs.session.serverCertificates
Adam Langley75712922014-10-10 16:23:43 -07001312 c.extendedMasterSecret = hs.session.extendedMasterSecret
Paul Lietar62be8ac2015-09-16 10:03:30 +01001313 c.sctList = hs.session.sctList
1314 c.ocspResponse = hs.session.ocspResponse
David Benjamine098ec22014-08-27 23:13:20 -04001315 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001316 return true, nil
1317 }
Paul Lietar62be8ac2015-09-16 10:03:30 +01001318
Nick Harperb3d51be2016-07-01 11:43:18 -04001319 if hs.serverHello.extensions.sctList != nil {
1320 c.sctList = hs.serverHello.extensions.sctList
Paul Lietar62be8ac2015-09-16 10:03:30 +01001321 }
1322
Adam Langley95c29f32014-06-20 12:00:00 -07001323 return false, nil
1324}
1325
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001326func (hs *clientHandshakeState) readFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001327 c := hs.c
1328
1329 c.readRecord(recordTypeChangeCipherSpec)
1330 if err := c.in.error(); err != nil {
1331 return err
1332 }
1333
1334 msg, err := c.readHandshake()
1335 if err != nil {
1336 return err
1337 }
1338 serverFinished, ok := msg.(*finishedMsg)
1339 if !ok {
1340 c.sendAlert(alertUnexpectedMessage)
1341 return unexpectedMessageError(serverFinished, msg)
1342 }
1343
David Benjaminf3ec83d2014-07-21 22:42:34 -04001344 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
1345 verify := hs.finishedHash.serverSum(hs.masterSecret)
1346 if len(verify) != len(serverFinished.verifyData) ||
1347 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
1348 c.sendAlert(alertHandshakeFailure)
1349 return errors.New("tls: server's Finished message was incorrect")
1350 }
Adam Langley95c29f32014-06-20 12:00:00 -07001351 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001352 c.serverVerify = append(c.serverVerify[:0], serverFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001353 copy(out, serverFinished.verifyData)
David Benjamin83c0bc92014-08-04 01:23:53 -04001354 hs.writeServerHash(serverFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001355 return nil
1356}
1357
1358func (hs *clientHandshakeState) readSessionTicket() error {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001359 c := hs.c
1360
1361 // Create a session with no server identifier. Either a
1362 // session ID or session ticket will be attached.
1363 session := &ClientSessionState{
1364 vers: c.vers,
1365 cipherSuite: hs.suite.id,
1366 masterSecret: hs.masterSecret,
Nick Harperc9846112016-10-17 15:05:35 -07001367 handshakeHash: hs.finishedHash.Sum(),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001368 serverCertificates: c.peerCertificates,
Paul Lietar62be8ac2015-09-16 10:03:30 +01001369 sctList: c.sctList,
1370 ocspResponse: c.ocspResponse,
Nick Harper0b3625b2016-07-25 16:16:28 -07001371 ticketExpiration: c.config.time().Add(time.Duration(7 * 24 * time.Hour)),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001372 }
1373
Nick Harperb3d51be2016-07-01 11:43:18 -04001374 if !hs.serverHello.extensions.ticketSupported {
David Benjamind98452d2015-06-16 14:16:23 -04001375 if c.config.Bugs.ExpectNewTicket {
1376 return errors.New("tls: expected new ticket")
1377 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001378 if hs.session == nil && len(hs.serverHello.sessionId) > 0 {
1379 session.sessionId = hs.serverHello.sessionId
1380 hs.session = session
1381 }
Adam Langley95c29f32014-06-20 12:00:00 -07001382 return nil
1383 }
1384
David Benjaminc7ce9772015-10-09 19:32:41 -04001385 if c.vers == VersionSSL30 {
1386 return errors.New("tls: negotiated session tickets in SSL 3.0")
1387 }
1388
Adam Langley95c29f32014-06-20 12:00:00 -07001389 msg, err := c.readHandshake()
1390 if err != nil {
1391 return err
1392 }
1393 sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
1394 if !ok {
1395 c.sendAlert(alertUnexpectedMessage)
1396 return unexpectedMessageError(sessionTicketMsg, msg)
1397 }
Adam Langley95c29f32014-06-20 12:00:00 -07001398
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001399 session.sessionTicket = sessionTicketMsg.ticket
1400 hs.session = session
Adam Langley95c29f32014-06-20 12:00:00 -07001401
David Benjamind30a9902014-08-24 01:44:23 -04001402 hs.writeServerHash(sessionTicketMsg.marshal())
1403
Adam Langley95c29f32014-06-20 12:00:00 -07001404 return nil
1405}
1406
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001407func (hs *clientHandshakeState) sendFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001408 c := hs.c
1409
David Benjamin0b8d5da2016-07-15 00:39:56 -04001410 var postCCSMsgs [][]byte
David Benjamin83c0bc92014-08-04 01:23:53 -04001411 seqno := hs.c.sendHandshakeSeq
Nick Harperb3d51be2016-07-01 11:43:18 -04001412 if hs.serverHello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001413 nextProto := new(nextProtoMsg)
Nick Harperb3d51be2016-07-01 11:43:18 -04001414 proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.extensions.nextProtos)
Adam Langley95c29f32014-06-20 12:00:00 -07001415 nextProto.proto = proto
1416 c.clientProtocol = proto
1417 c.clientProtocolFallback = fallback
1418
David Benjamin86271ee2014-07-21 16:14:03 -04001419 nextProtoBytes := nextProto.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -04001420 hs.writeHash(nextProtoBytes, seqno)
1421 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001422 postCCSMsgs = append(postCCSMsgs, nextProtoBytes)
Adam Langley95c29f32014-06-20 12:00:00 -07001423 }
1424
Nick Harperb3d51be2016-07-01 11:43:18 -04001425 if hs.serverHello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001426 var resumeHash []byte
1427 if isResume {
1428 resumeHash = hs.session.handshakeHash
1429 }
Nick Harper60a85cb2016-09-23 16:25:11 -07001430 channelIDMsgBytes, err := hs.writeChannelIDMessage(hs.finishedHash.hashForChannelID(resumeHash))
David Benjamind30a9902014-08-24 01:44:23 -04001431 if err != nil {
1432 return err
1433 }
David Benjamin24599a82016-06-30 18:56:53 -04001434 hs.writeHash(channelIDMsgBytes, seqno)
David Benjamind30a9902014-08-24 01:44:23 -04001435 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001436 postCCSMsgs = append(postCCSMsgs, channelIDMsgBytes)
David Benjamind30a9902014-08-24 01:44:23 -04001437 }
1438
Adam Langley95c29f32014-06-20 12:00:00 -07001439 finished := new(finishedMsg)
David Benjaminf3ec83d2014-07-21 22:42:34 -04001440 if c.config.Bugs.EarlyChangeCipherSpec == 2 {
1441 finished.verifyData = hs.finishedHash.clientSum(nil)
1442 } else {
1443 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
1444 }
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001445 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001446 if c.config.Bugs.BadFinished {
1447 finished.verifyData[0]++
1448 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001449 c.clientVerify = append(c.clientVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001450 hs.finishedBytes = finished.marshal()
1451 hs.writeHash(hs.finishedBytes, seqno)
David Benjamin0b8d5da2016-07-15 00:39:56 -04001452 postCCSMsgs = append(postCCSMsgs, hs.finishedBytes)
David Benjamin86271ee2014-07-21 16:14:03 -04001453
1454 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001455 c.writeRecord(recordTypeHandshake, postCCSMsgs[0][:5])
1456 postCCSMsgs[0] = postCCSMsgs[0][5:]
David Benjamin61672812016-07-14 23:10:43 -04001457 } else if c.config.Bugs.SendUnencryptedFinished {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001458 c.writeRecord(recordTypeHandshake, postCCSMsgs[0])
1459 postCCSMsgs = postCCSMsgs[1:]
David Benjamin86271ee2014-07-21 16:14:03 -04001460 }
David Benjamin582ba042016-07-07 12:33:25 -07001461 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001462
1463 if !c.config.Bugs.SkipChangeCipherSpec &&
1464 c.config.Bugs.EarlyChangeCipherSpec == 0 {
David Benjamin8411b242015-11-26 12:07:28 -05001465 ccs := []byte{1}
1466 if c.config.Bugs.BadChangeCipherSpec != nil {
1467 ccs = c.config.Bugs.BadChangeCipherSpec
1468 }
1469 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamin86271ee2014-07-21 16:14:03 -04001470 }
1471
David Benjamin4189bd92015-01-25 23:52:39 -05001472 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1473 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1474 }
David Benjamindc3da932015-03-12 15:09:02 -04001475 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1476 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1477 return errors.New("tls: simulating post-CCS alert")
1478 }
David Benjamin4189bd92015-01-25 23:52:39 -05001479
David Benjamin0b8d5da2016-07-15 00:39:56 -04001480 if !c.config.Bugs.SkipFinished {
1481 for _, msg := range postCCSMsgs {
1482 c.writeRecord(recordTypeHandshake, msg)
1483 }
David Benjamin02edcd02016-07-27 17:40:37 -04001484
1485 if c.config.Bugs.SendExtraFinished {
1486 c.writeRecord(recordTypeHandshake, finished.marshal())
1487 }
1488
David Benjamin582ba042016-07-07 12:33:25 -07001489 c.flushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -05001490 }
Adam Langley95c29f32014-06-20 12:00:00 -07001491 return nil
1492}
1493
Nick Harper60a85cb2016-09-23 16:25:11 -07001494func (hs *clientHandshakeState) writeChannelIDMessage(channelIDHash []byte) ([]byte, error) {
1495 c := hs.c
1496 channelIDMsg := new(channelIDMsg)
1497 if c.config.ChannelID.Curve != elliptic.P256() {
1498 return nil, fmt.Errorf("tls: Channel ID is not on P-256.")
1499 }
1500 r, s, err := ecdsa.Sign(c.config.rand(), c.config.ChannelID, channelIDHash)
1501 if err != nil {
1502 return nil, err
1503 }
1504 channelID := make([]byte, 128)
1505 writeIntPadded(channelID[0:32], c.config.ChannelID.X)
1506 writeIntPadded(channelID[32:64], c.config.ChannelID.Y)
1507 writeIntPadded(channelID[64:96], r)
1508 writeIntPadded(channelID[96:128], s)
1509 if c.config.Bugs.InvalidChannelIDSignature {
1510 channelID[64] ^= 1
1511 }
1512 channelIDMsg.channelID = channelID
1513
1514 c.channelID = &c.config.ChannelID.PublicKey
1515
1516 return channelIDMsg.marshal(), nil
1517}
1518
David Benjamin83c0bc92014-08-04 01:23:53 -04001519func (hs *clientHandshakeState) writeClientHash(msg []byte) {
1520 // writeClientHash is called before writeRecord.
1521 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1522}
1523
1524func (hs *clientHandshakeState) writeServerHash(msg []byte) {
1525 // writeServerHash is called after readHandshake.
1526 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1527}
1528
1529func (hs *clientHandshakeState) writeHash(msg []byte, seqno uint16) {
1530 if hs.c.isDTLS {
1531 // This is somewhat hacky. DTLS hashes a slightly different format.
1532 // First, the TLS header.
1533 hs.finishedHash.Write(msg[:4])
1534 // Then the sequence number and reassembled fragment offset (always 0).
1535 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1536 // Then the reassembled fragment (always equal to the message length).
1537 hs.finishedHash.Write(msg[1:4])
1538 // And then the message body.
1539 hs.finishedHash.Write(msg[4:])
1540 } else {
1541 hs.finishedHash.Write(msg)
1542 }
1543}
1544
David Benjamina6f82632016-07-01 18:44:02 -04001545// selectClientCertificate selects a certificate for use with the given
1546// certificate, or none if none match. It may return a particular certificate or
1547// nil on success, or an error on internal error.
1548func selectClientCertificate(c *Conn, certReq *certificateRequestMsg) (*Certificate, error) {
1549 // RFC 4346 on the certificateAuthorities field:
1550 // A list of the distinguished names of acceptable certificate
1551 // authorities. These distinguished names may specify a desired
1552 // distinguished name for a root CA or for a subordinate CA; thus, this
1553 // message can be used to describe both known roots and a desired
1554 // authorization space. If the certificate_authorities list is empty
1555 // then the client MAY send any certificate of the appropriate
1556 // ClientCertificateType, unless there is some external arrangement to
1557 // the contrary.
1558
1559 var rsaAvail, ecdsaAvail bool
Nick Harperb41d2e42016-07-01 17:50:32 -04001560 if !certReq.hasRequestContext {
1561 for _, certType := range certReq.certificateTypes {
1562 switch certType {
1563 case CertTypeRSASign:
1564 rsaAvail = true
1565 case CertTypeECDSASign:
1566 ecdsaAvail = true
1567 }
David Benjamina6f82632016-07-01 18:44:02 -04001568 }
1569 }
1570
1571 // We need to search our list of client certs for one
1572 // where SignatureAlgorithm is RSA and the Issuer is in
1573 // certReq.certificateAuthorities
1574findCert:
1575 for i, chain := range c.config.Certificates {
Nick Harperb41d2e42016-07-01 17:50:32 -04001576 if !certReq.hasRequestContext && !rsaAvail && !ecdsaAvail {
David Benjamina6f82632016-07-01 18:44:02 -04001577 continue
1578 }
1579
1580 // Ensure the private key supports one of the advertised
1581 // signature algorithms.
1582 if certReq.hasSignatureAlgorithm {
David Benjamin0a8deb22016-07-09 21:02:01 -07001583 if _, err := selectSignatureAlgorithm(c.vers, chain.PrivateKey, c.config, certReq.signatureAlgorithms); err != nil {
David Benjamina6f82632016-07-01 18:44:02 -04001584 continue
1585 }
1586 }
1587
1588 for j, cert := range chain.Certificate {
1589 x509Cert := chain.Leaf
1590 // parse the certificate if this isn't the leaf
1591 // node, or if chain.Leaf was nil
1592 if j != 0 || x509Cert == nil {
1593 var err error
1594 if x509Cert, err = x509.ParseCertificate(cert); err != nil {
1595 c.sendAlert(alertInternalError)
1596 return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
1597 }
1598 }
1599
Nick Harperb41d2e42016-07-01 17:50:32 -04001600 if !certReq.hasRequestContext {
1601 switch {
1602 case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
1603 case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
1604 default:
1605 continue findCert
1606 }
David Benjamina6f82632016-07-01 18:44:02 -04001607 }
1608
1609 if len(certReq.certificateAuthorities) == 0 {
1610 // They gave us an empty list, so just take the
1611 // first certificate of valid type from
1612 // c.config.Certificates.
1613 return &chain, nil
1614 }
1615
1616 for _, ca := range certReq.certificateAuthorities {
1617 if bytes.Equal(x509Cert.RawIssuer, ca) {
1618 return &chain, nil
1619 }
1620 }
1621 }
1622 }
1623
1624 return nil, nil
1625}
1626
Adam Langley95c29f32014-06-20 12:00:00 -07001627// clientSessionCacheKey returns a key used to cache sessionTickets that could
1628// be used to resume previously negotiated TLS sessions with a server.
1629func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
1630 if len(config.ServerName) > 0 {
1631 return config.ServerName
1632 }
1633 return serverAddr.String()
1634}
1635
David Benjaminfa055a22014-09-15 16:51:51 -04001636// mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
1637// given list of possible protocols and a list of the preference order. The
1638// first list must not be empty. It returns the resulting protocol and flag
Adam Langley95c29f32014-06-20 12:00:00 -07001639// indicating if the fallback case was reached.
David Benjaminfa055a22014-09-15 16:51:51 -04001640func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
1641 for _, s := range preferenceProtos {
1642 for _, c := range protos {
Adam Langley95c29f32014-06-20 12:00:00 -07001643 if s == c {
1644 return s, false
1645 }
1646 }
1647 }
1648
David Benjaminfa055a22014-09-15 16:51:51 -04001649 return protos[0], true
Adam Langley95c29f32014-06-20 12:00:00 -07001650}
David Benjamind30a9902014-08-24 01:44:23 -04001651
1652// writeIntPadded writes x into b, padded up with leading zeros as
1653// needed.
1654func writeIntPadded(b []byte, x *big.Int) {
1655 for i := range b {
1656 b[i] = 0
1657 }
1658 xb := x.Bytes()
1659 copy(b[len(b)-len(xb):], xb)
1660}
Steven Valdeza833c352016-11-01 13:39:36 -04001661
1662func generatePSKBinders(hello *clientHelloMsg, pskCipherSuite *cipherSuite, psk, transcript []byte, config *Config) {
1663 if config.Bugs.SendNoPSKBinder {
1664 return
1665 }
1666
1667 binderLen := pskCipherSuite.hash().Size()
1668 if config.Bugs.SendShortPSKBinder {
1669 binderLen--
1670 }
1671
David Benjaminaedf3032016-12-01 16:47:56 -05001672 numBinders := 1
1673 if config.Bugs.SendExtraPSKBinder {
1674 numBinders++
1675 }
1676
Steven Valdeza833c352016-11-01 13:39:36 -04001677 // Fill hello.pskBinders with appropriate length arrays of zeros so the
1678 // length prefixes are correct when computing the binder over the truncated
1679 // ClientHello message.
David Benjaminaedf3032016-12-01 16:47:56 -05001680 hello.pskBinders = make([][]byte, numBinders)
1681 for i := range hello.pskBinders {
Steven Valdeza833c352016-11-01 13:39:36 -04001682 hello.pskBinders[i] = make([]byte, binderLen)
1683 }
1684
1685 helloBytes := hello.marshal()
1686 binderSize := len(hello.pskBinders)*(binderLen+1) + 2
1687 truncatedHello := helloBytes[:len(helloBytes)-binderSize]
1688 binder := computePSKBinder(psk, resumptionPSKBinderLabel, pskCipherSuite, transcript, truncatedHello)
1689 if config.Bugs.SendShortPSKBinder {
1690 binder = binder[:binderLen]
1691 }
1692 if config.Bugs.SendInvalidPSKBinder {
1693 binder[0] ^= 1
1694 }
1695
1696 for i := range hello.pskBinders {
1697 hello.pskBinders[i] = binder
1698 }
1699
1700 hello.raw = nil
1701}