blob: 208dcca9c4bcfbd965650d56effdb6d40c2c057d [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
Steven Valdez803c77a2016-09-06 14:13:43 -0400226 for _, id := range hello.cipherSuites {
227 if id == candidateSession.cipherSuite {
228 cipherSuiteOk = true
229 break
Adam Langley95c29f32014-06-20 12:00:00 -0700230 }
231 }
232
Steven Valdezfdd10992016-09-15 16:27:05 -0400233 versOk := candidateSession.vers >= minVersion &&
234 candidateSession.vers <= maxVersion
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500235 if ticketOk && versOk && cipherSuiteOk {
Adam Langley95c29f32014-06-20 12:00:00 -0700236 session = candidateSession
237 }
238 }
239 }
240
Steven Valdeza833c352016-11-01 13:39:36 -0400241 var pskCipherSuite *cipherSuite
Nick Harper0b3625b2016-07-25 16:16:28 -0700242 if session != nil && c.config.time().Before(session.ticketExpiration) {
David Benjamind5a4ecb2016-07-18 01:17:13 +0200243 ticket := session.sessionTicket
David Benjamin4199b0d2016-11-01 13:58:25 -0400244 if c.config.Bugs.FilterTicket != nil && len(ticket) > 0 {
245 // Copy the ticket so FilterTicket may act in-place.
David Benjamind5a4ecb2016-07-18 01:17:13 +0200246 ticket = make([]byte, len(session.sessionTicket))
247 copy(ticket, session.sessionTicket)
David Benjamin4199b0d2016-11-01 13:58:25 -0400248
249 ticket, err = c.config.Bugs.FilterTicket(ticket)
250 if err != nil {
251 return err
Adam Langley38311732014-10-16 19:04:35 -0700252 }
David Benjamind5a4ecb2016-07-18 01:17:13 +0200253 }
254
David Benjamin405da482016-08-08 17:25:07 -0400255 if session.vers >= VersionTLS13 || c.config.Bugs.SendBothTickets {
Steven Valdeza833c352016-11-01 13:39:36 -0400256 pskCipherSuite = cipherSuiteFromID(session.cipherSuite)
257 if pskCipherSuite == nil {
258 return errors.New("tls: client session cache has invalid cipher suite")
259 }
Nick Harper0b3625b2016-07-25 16:16:28 -0700260 // TODO(nharper): Support sending more
261 // than one PSK identity.
Steven Valdeza833c352016-11-01 13:39:36 -0400262 ticketAge := uint32(c.config.time().Sub(session.ticketCreationTime) / time.Millisecond)
Steven Valdez5b986082016-09-01 12:29:49 -0400263 psk := pskIdentity{
Steven Valdeza833c352016-11-01 13:39:36 -0400264 ticket: ticket,
265 obfuscatedTicketAge: session.ticketAgeAdd + ticketAge,
Nick Harper0b3625b2016-07-25 16:16:28 -0700266 }
Steven Valdez5b986082016-09-01 12:29:49 -0400267 hello.pskIdentities = []pskIdentity{psk}
Steven Valdezaf3b8a92016-11-01 12:49:22 -0400268
269 if c.config.Bugs.ExtraPSKIdentity {
270 hello.pskIdentities = append(hello.pskIdentities, psk)
271 }
David Benjamin405da482016-08-08 17:25:07 -0400272 }
273
274 if session.vers < VersionTLS13 || c.config.Bugs.SendBothTickets {
275 if ticket != nil {
276 hello.sessionTicket = ticket
277 // A random session ID is used to detect when the
278 // server accepted the ticket and is resuming a session
279 // (see RFC 5077).
280 sessionIdLen := 16
281 if c.config.Bugs.OversizedSessionId {
282 sessionIdLen = 33
283 }
284 hello.sessionId = make([]byte, sessionIdLen)
285 if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
286 c.sendAlert(alertInternalError)
287 return errors.New("tls: short read from Rand: " + err.Error())
288 }
289 } else {
290 hello.sessionId = session.sessionId
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500291 }
Adam Langley95c29f32014-06-20 12:00:00 -0700292 }
293 }
294
Steven Valdezfdd10992016-09-15 16:27:05 -0400295 if maxVersion == VersionTLS13 && !c.config.Bugs.OmitSupportedVersions {
296 if hello.vers >= VersionTLS13 {
297 hello.vers = VersionTLS12
298 }
299 for version := maxVersion; version >= minVersion; version-- {
300 hello.supportedVersions = append(hello.supportedVersions, versionToWire(version, c.isDTLS))
301 }
302 }
303
304 if len(c.config.Bugs.SendSupportedVersions) > 0 {
305 hello.supportedVersions = c.config.Bugs.SendSupportedVersions
306 }
307
David Benjamineed24012016-08-13 19:26:00 -0400308 if c.config.Bugs.SendClientVersion != 0 {
309 hello.vers = c.config.Bugs.SendClientVersion
310 }
311
David Benjamin75f99142016-11-12 12:36:06 +0900312 if c.config.Bugs.SendCipherSuites != nil {
313 hello.cipherSuites = c.config.Bugs.SendCipherSuites
314 }
315
David Benjamind86c7672014-08-02 04:07:12 -0400316 var helloBytes []byte
317 if c.config.Bugs.SendV2ClientHello {
David Benjamin94d701b2014-11-30 13:54:41 -0500318 // Test that the peer left-pads random.
319 hello.random[0] = 0
David Benjamind86c7672014-08-02 04:07:12 -0400320 v2Hello := &v2ClientHelloMsg{
321 vers: hello.vers,
322 cipherSuites: hello.cipherSuites,
323 // No session resumption for V2ClientHello.
324 sessionId: nil,
David Benjamin94d701b2014-11-30 13:54:41 -0500325 challenge: hello.random[1:],
David Benjamind86c7672014-08-02 04:07:12 -0400326 }
327 helloBytes = v2Hello.marshal()
328 c.writeV2Record(helloBytes)
329 } else {
Steven Valdeza833c352016-11-01 13:39:36 -0400330 if len(hello.pskIdentities) > 0 {
331 generatePSKBinders(hello, pskCipherSuite, session.masterSecret, []byte{}, c.config)
332 }
David Benjamind86c7672014-08-02 04:07:12 -0400333 helloBytes = hello.marshal()
Steven Valdeza833c352016-11-01 13:39:36 -0400334
David Benjamin7964b182016-07-14 23:36:30 -0400335 if c.config.Bugs.PartialClientFinishedWithClientHello {
336 // Include one byte of Finished. We can compute it
337 // without completing the handshake. This assumes we
338 // negotiate TLS 1.3 with no HelloRetryRequest or
339 // CertificateRequest.
340 toWrite := make([]byte, 0, len(helloBytes)+1)
341 toWrite = append(toWrite, helloBytes...)
342 toWrite = append(toWrite, typeFinished)
343 c.writeRecord(recordTypeHandshake, toWrite)
344 } else {
345 c.writeRecord(recordTypeHandshake, helloBytes)
346 }
David Benjamind86c7672014-08-02 04:07:12 -0400347 }
David Benjamin582ba042016-07-07 12:33:25 -0700348 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700349
David Benjamin83f90402015-01-27 01:09:43 -0500350 if err := c.simulatePacketLoss(nil); err != nil {
351 return err
352 }
Adam Langley95c29f32014-06-20 12:00:00 -0700353 msg, err := c.readHandshake()
354 if err != nil {
355 return err
356 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400357
358 if c.isDTLS {
359 helloVerifyRequest, ok := msg.(*helloVerifyRequestMsg)
360 if ok {
David Benjaminda4789e2016-10-31 19:23:34 -0400361 if helloVerifyRequest.vers != versionToWire(VersionTLS10, c.isDTLS) {
David Benjamin8bc38f52014-08-16 12:07:27 -0400362 // Per RFC 6347, the version field in
363 // HelloVerifyRequest SHOULD be always DTLS
364 // 1.0. Enforce this for testing purposes.
365 return errors.New("dtls: bad HelloVerifyRequest version")
366 }
367
David Benjamin83c0bc92014-08-04 01:23:53 -0400368 hello.raw = nil
369 hello.cookie = helloVerifyRequest.cookie
370 helloBytes = hello.marshal()
371 c.writeRecord(recordTypeHandshake, helloBytes)
David Benjamin582ba042016-07-07 12:33:25 -0700372 c.flushHandshake()
David Benjamin83c0bc92014-08-04 01:23:53 -0400373
David Benjamin83f90402015-01-27 01:09:43 -0500374 if err := c.simulatePacketLoss(nil); err != nil {
375 return err
376 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400377 msg, err = c.readHandshake()
378 if err != nil {
379 return err
380 }
381 }
382 }
383
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400384 var serverWireVersion uint16
Nick Harperdcfbc672016-07-16 17:47:31 +0200385 switch m := msg.(type) {
386 case *helloRetryRequestMsg:
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400387 serverWireVersion = m.vers
Nick Harperdcfbc672016-07-16 17:47:31 +0200388 case *serverHelloMsg:
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400389 serverWireVersion = m.vers
Nick Harperdcfbc672016-07-16 17:47:31 +0200390 default:
391 c.sendAlert(alertUnexpectedMessage)
392 return fmt.Errorf("tls: received unexpected message of type %T when waiting for HelloRetryRequest or ServerHello", msg)
393 }
394
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400395 serverVersion, ok := wireToVersion(serverWireVersion, c.isDTLS)
396 if ok {
Steven Valdezfdd10992016-09-15 16:27:05 -0400397 ok = c.config.isSupportedVersion(serverVersion, c.isDTLS)
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400398 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200399 if !ok {
400 c.sendAlert(alertProtocolVersion)
401 return fmt.Errorf("tls: server selected unsupported protocol version %x", c.vers)
402 }
Steven Valdezfdd10992016-09-15 16:27:05 -0400403 c.vers = serverVersion
Nick Harperdcfbc672016-07-16 17:47:31 +0200404 c.haveVers = true
405
406 helloRetryRequest, haveHelloRetryRequest := msg.(*helloRetryRequestMsg)
407 var secondHelloBytes []byte
408 if haveHelloRetryRequest {
David Benjamin3baa6e12016-10-07 21:10:38 -0400409 if len(helloRetryRequest.cookie) > 0 {
410 hello.tls13Cookie = helloRetryRequest.cookie
411 }
412
Steven Valdez5440fe02016-07-18 12:40:30 -0400413 if c.config.Bugs.MisinterpretHelloRetryRequestCurve != 0 {
David Benjamin3baa6e12016-10-07 21:10:38 -0400414 helloRetryRequest.hasSelectedGroup = true
Steven Valdez5440fe02016-07-18 12:40:30 -0400415 helloRetryRequest.selectedGroup = c.config.Bugs.MisinterpretHelloRetryRequestCurve
416 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400417 if helloRetryRequest.hasSelectedGroup {
418 var hrrCurveFound bool
419 group := helloRetryRequest.selectedGroup
420 for _, curveID := range hello.supportedCurves {
421 if group == curveID {
422 hrrCurveFound = true
423 break
424 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200425 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400426 if !hrrCurveFound || keyShares[group] != nil {
427 c.sendAlert(alertHandshakeFailure)
428 return errors.New("tls: received invalid HelloRetryRequest")
429 }
430 curve, ok := curveForCurveID(group)
431 if !ok {
432 return errors.New("tls: Unable to get curve requested in HelloRetryRequest")
433 }
434 publicKey, err := curve.offer(c.config.rand())
435 if err != nil {
436 return err
437 }
438 keyShares[group] = curve
Steven Valdeza833c352016-11-01 13:39:36 -0400439 hello.keyShares = []keyShareEntry{{
David Benjamin3baa6e12016-10-07 21:10:38 -0400440 group: group,
441 keyExchange: publicKey,
Steven Valdeza833c352016-11-01 13:39:36 -0400442 }}
Nick Harperdcfbc672016-07-16 17:47:31 +0200443 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200444
Steven Valdez5440fe02016-07-18 12:40:30 -0400445 if c.config.Bugs.SecondClientHelloMissingKeyShare {
446 hello.hasKeyShares = false
447 }
448
Nick Harperdcfbc672016-07-16 17:47:31 +0200449 hello.hasEarlyData = false
Nick Harperdcfbc672016-07-16 17:47:31 +0200450 hello.raw = nil
451
Steven Valdeza833c352016-11-01 13:39:36 -0400452 if len(hello.pskIdentities) > 0 {
453 generatePSKBinders(hello, pskCipherSuite, session.masterSecret, append(helloBytes, helloRetryRequest.marshal()...), c.config)
454 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200455 secondHelloBytes = hello.marshal()
456 c.writeRecord(recordTypeHandshake, secondHelloBytes)
457 c.flushHandshake()
458
459 msg, err = c.readHandshake()
460 if err != nil {
461 return err
462 }
463 }
464
Adam Langley95c29f32014-06-20 12:00:00 -0700465 serverHello, ok := msg.(*serverHelloMsg)
466 if !ok {
467 c.sendAlert(alertUnexpectedMessage)
468 return unexpectedMessageError(serverHello, msg)
469 }
470
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400471 if serverWireVersion != serverHello.vers {
Adam Langley95c29f32014-06-20 12:00:00 -0700472 c.sendAlert(alertProtocolVersion)
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400473 return fmt.Errorf("tls: server sent non-matching version %x vs %x", serverWireVersion, serverHello.vers)
Adam Langley95c29f32014-06-20 12:00:00 -0700474 }
Adam Langley95c29f32014-06-20 12:00:00 -0700475
Nick Harper85f20c22016-07-04 10:11:59 -0700476 // Check for downgrade signals in the server random, per
David Benjamina128a552016-10-13 14:26:33 -0400477 // draft-ietf-tls-tls13-16, section 4.1.3.
Nick Harper85f20c22016-07-04 10:11:59 -0700478 if c.vers <= VersionTLS12 && c.config.maxVersion(c.isDTLS) >= VersionTLS13 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400479 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS13) {
Nick Harper85f20c22016-07-04 10:11:59 -0700480 c.sendAlert(alertProtocolVersion)
481 return errors.New("tls: downgrade from TLS 1.3 detected")
482 }
483 }
484 if c.vers <= VersionTLS11 && c.config.maxVersion(c.isDTLS) >= VersionTLS12 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400485 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS12) {
Nick Harper85f20c22016-07-04 10:11:59 -0700486 c.sendAlert(alertProtocolVersion)
487 return errors.New("tls: downgrade from TLS 1.2 detected")
488 }
489 }
490
Nick Harper0b3625b2016-07-25 16:16:28 -0700491 suite := mutualCipherSuite(hello.cipherSuites, serverHello.cipherSuite)
Adam Langley95c29f32014-06-20 12:00:00 -0700492 if suite == nil {
493 c.sendAlert(alertHandshakeFailure)
494 return fmt.Errorf("tls: server selected an unsupported cipher suite")
495 }
496
David Benjamin3baa6e12016-10-07 21:10:38 -0400497 if haveHelloRetryRequest && helloRetryRequest.hasSelectedGroup && helloRetryRequest.selectedGroup != serverHello.keyShare.group {
Nick Harperdcfbc672016-07-16 17:47:31 +0200498 c.sendAlert(alertHandshakeFailure)
499 return errors.New("tls: ServerHello parameters did not match HelloRetryRequest")
500 }
501
Adam Langley95c29f32014-06-20 12:00:00 -0700502 hs := &clientHandshakeState{
503 c: c,
504 serverHello: serverHello,
505 hello: hello,
506 suite: suite,
507 finishedHash: newFinishedHash(c.vers, suite),
Nick Harperb41d2e42016-07-01 17:50:32 -0400508 keyShares: keyShares,
Adam Langley95c29f32014-06-20 12:00:00 -0700509 session: session,
510 }
511
David Benjamin83c0bc92014-08-04 01:23:53 -0400512 hs.writeHash(helloBytes, hs.c.sendHandshakeSeq-1)
Nick Harperdcfbc672016-07-16 17:47:31 +0200513 if haveHelloRetryRequest {
514 hs.writeServerHash(helloRetryRequest.marshal())
515 hs.writeClientHash(secondHelloBytes)
516 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400517 hs.writeServerHash(hs.serverHello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700518
David Benjamin8d315d72016-07-18 01:03:18 +0200519 if c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -0400520 if err := hs.doTLS13Handshake(); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700521 return err
522 }
523 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400524 if c.config.Bugs.EarlyChangeCipherSpec > 0 {
525 hs.establishKeys()
526 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
527 }
528
529 if hs.serverHello.compressionMethod != compressionNone {
530 c.sendAlert(alertUnexpectedMessage)
531 return errors.New("tls: server selected unsupported compression format")
532 }
533
534 err = hs.processServerExtensions(&serverHello.extensions)
535 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700536 return err
537 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400538
539 isResume, err := hs.processServerHello()
540 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700541 return err
542 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400543
544 if isResume {
545 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
546 if err := hs.establishKeys(); err != nil {
547 return err
548 }
549 }
550 if err := hs.readSessionTicket(); err != nil {
551 return err
552 }
553 if err := hs.readFinished(c.firstFinished[:]); err != nil {
554 return err
555 }
556 if err := hs.sendFinished(nil, isResume); err != nil {
557 return err
558 }
559 } else {
560 if err := hs.doFullHandshake(); err != nil {
561 return err
562 }
563 if err := hs.establishKeys(); err != nil {
564 return err
565 }
566 if err := hs.sendFinished(c.firstFinished[:], isResume); err != nil {
567 return err
568 }
569 // Most retransmits are triggered by a timeout, but the final
570 // leg of the handshake is retransmited upon re-receiving a
571 // Finished.
572 if err := c.simulatePacketLoss(func() {
David Benjamin02edcd02016-07-27 17:40:37 -0400573 c.sendHandshakeSeq--
Nick Harperb41d2e42016-07-01 17:50:32 -0400574 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
575 c.flushHandshake()
576 }); err != nil {
577 return err
578 }
579 if err := hs.readSessionTicket(); err != nil {
580 return err
581 }
582 if err := hs.readFinished(nil); err != nil {
583 return err
584 }
Adam Langley95c29f32014-06-20 12:00:00 -0700585 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400586
587 if sessionCache != nil && hs.session != nil && session != hs.session {
588 if c.config.Bugs.RequireSessionTickets && len(hs.session.sessionTicket) == 0 {
589 return errors.New("tls: new session used session IDs instead of tickets")
590 }
591 sessionCache.Put(cacheKey, hs.session)
David Benjamin83f90402015-01-27 01:09:43 -0500592 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400593
594 c.didResume = isResume
David Benjamin97a0a082016-07-13 17:57:35 -0400595 c.exporterSecret = hs.masterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700596 }
597
Adam Langley95c29f32014-06-20 12:00:00 -0700598 c.handshakeComplete = true
David Benjaminc565ebb2015-04-03 04:06:36 -0400599 c.cipherSuite = suite
600 copy(c.clientRandom[:], hs.hello.random)
601 copy(c.serverRandom[:], hs.serverHello.random)
Paul Lietar4fac72e2015-09-09 13:44:55 +0100602
Adam Langley95c29f32014-06-20 12:00:00 -0700603 return nil
604}
605
Nick Harperb41d2e42016-07-01 17:50:32 -0400606func (hs *clientHandshakeState) doTLS13Handshake() error {
607 c := hs.c
608
609 // Once the PRF hash is known, TLS 1.3 does not require a handshake
610 // buffer.
611 hs.finishedHash.discardHandshakeBuffer()
612
613 zeroSecret := hs.finishedHash.zeroSecret()
614
615 // Resolve PSK and compute the early secret.
616 //
617 // TODO(davidben): This will need to be handled slightly earlier once
618 // 0-RTT is implemented.
619 var psk []byte
Steven Valdez803c77a2016-09-06 14:13:43 -0400620 if hs.serverHello.hasPSKIdentity {
Nick Harper0b3625b2016-07-25 16:16:28 -0700621 // We send at most one PSK identity.
622 if hs.session == nil || hs.serverHello.pskIdentity != 0 {
623 c.sendAlert(alertUnknownPSKIdentity)
624 return errors.New("tls: server sent unknown PSK identity")
625 }
Steven Valdez803c77a2016-09-06 14:13:43 -0400626 if hs.session.cipherSuite != hs.suite.id {
Nick Harper0b3625b2016-07-25 16:16:28 -0700627 c.sendAlert(alertHandshakeFailure)
Steven Valdez803c77a2016-09-06 14:13:43 -0400628 return errors.New("tls: server sent invalid cipher suite")
Nick Harper0b3625b2016-07-25 16:16:28 -0700629 }
Steven Valdeza833c352016-11-01 13:39:36 -0400630 psk = hs.session.masterSecret
Nick Harper0b3625b2016-07-25 16:16:28 -0700631 c.didResume = true
Nick Harperb41d2e42016-07-01 17:50:32 -0400632 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400633 psk = zeroSecret
Nick Harperb41d2e42016-07-01 17:50:32 -0400634 }
635
636 earlySecret := hs.finishedHash.extractKey(zeroSecret, psk)
637
Steven Valdeza833c352016-11-01 13:39:36 -0400638 if !hs.serverHello.hasKeyShare {
639 c.sendAlert(alertUnsupportedExtension)
640 return errors.New("tls: server omitted KeyShare on resumption.")
641 }
642
Nick Harperb41d2e42016-07-01 17:50:32 -0400643 // Resolve ECDHE and compute the handshake secret.
644 var ecdheSecret []byte
Steven Valdez803c77a2016-09-06 14:13:43 -0400645 if !c.config.Bugs.MissingKeyShare && !c.config.Bugs.SecondClientHelloMissingKeyShare {
Nick Harperb41d2e42016-07-01 17:50:32 -0400646 curve, ok := hs.keyShares[hs.serverHello.keyShare.group]
647 if !ok {
648 c.sendAlert(alertHandshakeFailure)
649 return errors.New("tls: server selected an unsupported group")
650 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400651 c.curveID = hs.serverHello.keyShare.group
Nick Harperb41d2e42016-07-01 17:50:32 -0400652
653 var err error
654 ecdheSecret, err = curve.finish(hs.serverHello.keyShare.keyExchange)
655 if err != nil {
656 return err
657 }
658 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400659 ecdheSecret = zeroSecret
660 }
661
662 // Compute the handshake secret.
663 handshakeSecret := hs.finishedHash.extractKey(earlySecret, ecdheSecret)
664
665 // Switch to handshake traffic keys.
Steven Valdezc4aa7272016-10-03 12:25:56 -0400666 clientHandshakeTrafficSecret := hs.finishedHash.deriveSecret(handshakeSecret, clientHandshakeTrafficLabel)
Steven Valdeza833c352016-11-01 13:39:36 -0400667 c.out.useTrafficSecret(c.vers, hs.suite, clientHandshakeTrafficSecret, clientWrite)
Steven Valdezc4aa7272016-10-03 12:25:56 -0400668 serverHandshakeTrafficSecret := hs.finishedHash.deriveSecret(handshakeSecret, serverHandshakeTrafficLabel)
Steven Valdeza833c352016-11-01 13:39:36 -0400669 c.in.useTrafficSecret(c.vers, hs.suite, serverHandshakeTrafficSecret, serverWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -0400670
671 msg, err := c.readHandshake()
672 if err != nil {
673 return err
674 }
675
676 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
677 if !ok {
678 c.sendAlert(alertUnexpectedMessage)
679 return unexpectedMessageError(encryptedExtensions, msg)
680 }
681 hs.writeServerHash(encryptedExtensions.marshal())
682
683 err = hs.processServerExtensions(&encryptedExtensions.extensions)
684 if err != nil {
685 return err
686 }
687
688 var chainToSend *Certificate
David Benjamin8d343b42016-07-09 14:26:01 -0700689 var certReq *certificateRequestMsg
Steven Valdeza833c352016-11-01 13:39:36 -0400690 if c.didResume {
Nick Harper0b3625b2016-07-25 16:16:28 -0700691 // Copy over authentication from the session.
692 c.peerCertificates = hs.session.serverCertificates
693 c.sctList = hs.session.sctList
694 c.ocspResponse = hs.session.ocspResponse
David Benjamin44b33bc2016-07-01 22:40:23 -0400695 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400696 msg, err := c.readHandshake()
697 if err != nil {
698 return err
699 }
700
David Benjamin8d343b42016-07-09 14:26:01 -0700701 var ok bool
702 certReq, ok = msg.(*certificateRequestMsg)
Nick Harperb41d2e42016-07-01 17:50:32 -0400703 if ok {
David Benjamin8a8349b2016-08-18 02:32:23 -0400704 if len(certReq.requestContext) != 0 {
705 return errors.New("tls: non-empty certificate request context sent in handshake")
706 }
707
David Benjaminb62d2872016-07-18 14:55:02 +0200708 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
709 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
710 }
711
Nick Harperb41d2e42016-07-01 17:50:32 -0400712 hs.writeServerHash(certReq.marshal())
Nick Harperb41d2e42016-07-01 17:50:32 -0400713
714 chainToSend, err = selectClientCertificate(c, certReq)
715 if err != nil {
716 return err
717 }
718
719 msg, err = c.readHandshake()
720 if err != nil {
721 return err
722 }
723 }
724
725 certMsg, ok := msg.(*certificateMsg)
726 if !ok {
727 c.sendAlert(alertUnexpectedMessage)
728 return unexpectedMessageError(certMsg, msg)
729 }
730 hs.writeServerHash(certMsg.marshal())
731
David Benjamin53210cb2016-11-16 09:01:48 +0900732 // Check for unsolicited extensions.
733 for i, cert := range certMsg.certificates {
734 if c.config.Bugs.NoOCSPStapling && cert.ocspResponse != nil {
735 c.sendAlert(alertUnsupportedExtension)
736 return errors.New("tls: unexpected OCSP response in the server certificate")
737 }
738 if c.config.Bugs.NoSignedCertificateTimestamps && cert.sctList != nil {
739 c.sendAlert(alertUnsupportedExtension)
740 return errors.New("tls: unexpected SCT list in the server certificate")
741 }
742 if i > 0 && c.config.Bugs.ExpectNoExtensionsOnIntermediate && (cert.ocspResponse != nil || cert.sctList != nil) {
743 c.sendAlert(alertUnsupportedExtension)
744 return errors.New("tls: unexpected extensions in the server certificate")
745 }
746 }
747
Nick Harperb41d2e42016-07-01 17:50:32 -0400748 if err := hs.verifyCertificates(certMsg); err != nil {
749 return err
750 }
751 leaf := c.peerCertificates[0]
Steven Valdeza833c352016-11-01 13:39:36 -0400752 c.ocspResponse = certMsg.certificates[0].ocspResponse
753 c.sctList = certMsg.certificates[0].sctList
754
Nick Harperb41d2e42016-07-01 17:50:32 -0400755 msg, err = c.readHandshake()
756 if err != nil {
757 return err
758 }
759 certVerifyMsg, ok := msg.(*certificateVerifyMsg)
760 if !ok {
761 c.sendAlert(alertUnexpectedMessage)
762 return unexpectedMessageError(certVerifyMsg, msg)
763 }
764
David Benjaminf74ec792016-07-13 21:18:49 -0400765 c.peerSignatureAlgorithm = certVerifyMsg.signatureAlgorithm
Nick Harperb41d2e42016-07-01 17:50:32 -0400766 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
David Benjamin1fb125c2016-07-08 18:52:12 -0700767 err = verifyMessage(c.vers, leaf.PublicKey, c.config, certVerifyMsg.signatureAlgorithm, input, certVerifyMsg.signature)
Nick Harperb41d2e42016-07-01 17:50:32 -0400768 if err != nil {
769 return err
770 }
771
772 hs.writeServerHash(certVerifyMsg.marshal())
773 }
774
775 msg, err = c.readHandshake()
776 if err != nil {
777 return err
778 }
779 serverFinished, ok := msg.(*finishedMsg)
780 if !ok {
781 c.sendAlert(alertUnexpectedMessage)
782 return unexpectedMessageError(serverFinished, msg)
783 }
784
Steven Valdezc4aa7272016-10-03 12:25:56 -0400785 verify := hs.finishedHash.serverSum(serverHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400786 if len(verify) != len(serverFinished.verifyData) ||
787 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
788 c.sendAlert(alertHandshakeFailure)
789 return errors.New("tls: server's Finished message was incorrect")
790 }
791
792 hs.writeServerHash(serverFinished.marshal())
793
794 // The various secrets do not incorporate the client's final leg, so
795 // derive them now before updating the handshake context.
796 masterSecret := hs.finishedHash.extractKey(handshakeSecret, zeroSecret)
Steven Valdezc4aa7272016-10-03 12:25:56 -0400797 clientTrafficSecret := hs.finishedHash.deriveSecret(masterSecret, clientApplicationTrafficLabel)
798 serverTrafficSecret := hs.finishedHash.deriveSecret(masterSecret, serverApplicationTrafficLabel)
Nick Harperb41d2e42016-07-01 17:50:32 -0400799
Steven Valdez0ee2e112016-07-15 06:51:15 -0400800 if certReq != nil && !c.config.Bugs.SkipClientCertificate {
David Benjamin8d343b42016-07-09 14:26:01 -0700801 certMsg := &certificateMsg{
802 hasRequestContext: true,
803 requestContext: certReq.requestContext,
804 }
805 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -0400806 for _, certData := range chainToSend.Certificate {
807 certMsg.certificates = append(certMsg.certificates, certificateEntry{
808 data: certData,
809 extraExtension: c.config.Bugs.SendExtensionOnCertificate,
810 })
811 }
David Benjamin8d343b42016-07-09 14:26:01 -0700812 }
813 hs.writeClientHash(certMsg.marshal())
814 c.writeRecord(recordTypeHandshake, certMsg.marshal())
815
816 if chainToSend != nil {
817 certVerify := &certificateVerifyMsg{
818 hasSignatureAlgorithm: true,
819 }
820
821 // Determine the hash to sign.
822 privKey := chainToSend.PrivateKey
823
824 var err error
825 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
826 if err != nil {
827 c.sendAlert(alertInternalError)
828 return err
829 }
830
831 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
832 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
833 if err != nil {
834 c.sendAlert(alertInternalError)
835 return err
836 }
Steven Valdez0ee2e112016-07-15 06:51:15 -0400837 if c.config.Bugs.SendSignatureAlgorithm != 0 {
838 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
839 }
David Benjamin8d343b42016-07-09 14:26:01 -0700840
841 hs.writeClientHash(certVerify.marshal())
842 c.writeRecord(recordTypeHandshake, certVerify.marshal())
843 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400844 }
845
Nick Harper60a85cb2016-09-23 16:25:11 -0700846 if encryptedExtensions.extensions.channelIDRequested {
847 channelIDHash := crypto.SHA256.New()
848 channelIDHash.Write(hs.finishedHash.certificateVerifyInput(channelIDContextTLS13))
849 channelIDMsgBytes, err := hs.writeChannelIDMessage(channelIDHash.Sum(nil))
850 if err != nil {
851 return err
852 }
853 hs.writeClientHash(channelIDMsgBytes)
854 c.writeRecord(recordTypeHandshake, channelIDMsgBytes)
855 }
856
Nick Harperb41d2e42016-07-01 17:50:32 -0400857 // Send a client Finished message.
858 finished := new(finishedMsg)
Steven Valdezc4aa7272016-10-03 12:25:56 -0400859 finished.verifyData = hs.finishedHash.clientSum(clientHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400860 if c.config.Bugs.BadFinished {
861 finished.verifyData[0]++
862 }
David Benjamin97a0a082016-07-13 17:57:35 -0400863 hs.writeClientHash(finished.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400864 if c.config.Bugs.PartialClientFinishedWithClientHello {
865 // The first byte has already been sent.
866 c.writeRecord(recordTypeHandshake, finished.marshal()[1:])
867 } else {
868 c.writeRecord(recordTypeHandshake, finished.marshal())
869 }
David Benjamin02edcd02016-07-27 17:40:37 -0400870 if c.config.Bugs.SendExtraFinished {
871 c.writeRecord(recordTypeHandshake, finished.marshal())
872 }
David Benjaminee51a222016-07-07 18:34:12 -0700873 c.flushHandshake()
Nick Harperb41d2e42016-07-01 17:50:32 -0400874
875 // Switch to application data keys.
Steven Valdeza833c352016-11-01 13:39:36 -0400876 c.out.useTrafficSecret(c.vers, hs.suite, clientTrafficSecret, clientWrite)
877 c.in.useTrafficSecret(c.vers, hs.suite, serverTrafficSecret, serverWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -0400878
David Benjamin97a0a082016-07-13 17:57:35 -0400879 c.exporterSecret = hs.finishedHash.deriveSecret(masterSecret, exporterLabel)
David Benjamind5a4ecb2016-07-18 01:17:13 +0200880 c.resumptionSecret = hs.finishedHash.deriveSecret(masterSecret, resumptionLabel)
Nick Harperb41d2e42016-07-01 17:50:32 -0400881 return nil
882}
883
Adam Langley95c29f32014-06-20 12:00:00 -0700884func (hs *clientHandshakeState) doFullHandshake() error {
885 c := hs.c
886
David Benjamin48cae082014-10-27 01:06:24 -0400887 var leaf *x509.Certificate
888 if hs.suite.flags&suitePSK == 0 {
889 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700890 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700891 return err
892 }
Adam Langley95c29f32014-06-20 12:00:00 -0700893
David Benjamin48cae082014-10-27 01:06:24 -0400894 certMsg, ok := msg.(*certificateMsg)
David Benjamin75051442016-07-01 18:58:51 -0400895 if !ok {
David Benjamin48cae082014-10-27 01:06:24 -0400896 c.sendAlert(alertUnexpectedMessage)
897 return unexpectedMessageError(certMsg, msg)
898 }
899 hs.writeServerHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700900
David Benjamin75051442016-07-01 18:58:51 -0400901 if err := hs.verifyCertificates(certMsg); err != nil {
902 return err
David Benjamin48cae082014-10-27 01:06:24 -0400903 }
David Benjamin75051442016-07-01 18:58:51 -0400904 leaf = c.peerCertificates[0]
David Benjamin48cae082014-10-27 01:06:24 -0400905 }
Adam Langley95c29f32014-06-20 12:00:00 -0700906
Nick Harperb3d51be2016-07-01 11:43:18 -0400907 if hs.serverHello.extensions.ocspStapling {
David Benjamin48cae082014-10-27 01:06:24 -0400908 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700909 if err != nil {
910 return err
911 }
912 cs, ok := msg.(*certificateStatusMsg)
913 if !ok {
914 c.sendAlert(alertUnexpectedMessage)
915 return unexpectedMessageError(cs, msg)
916 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400917 hs.writeServerHash(cs.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700918
919 if cs.statusType == statusTypeOCSP {
920 c.ocspResponse = cs.response
921 }
922 }
923
David Benjamin48cae082014-10-27 01:06:24 -0400924 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700925 if err != nil {
926 return err
927 }
928
929 keyAgreement := hs.suite.ka(c.vers)
930
931 skx, ok := msg.(*serverKeyExchangeMsg)
932 if ok {
David Benjamin83c0bc92014-08-04 01:23:53 -0400933 hs.writeServerHash(skx.marshal())
David Benjamin48cae082014-10-27 01:06:24 -0400934 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, leaf, skx)
Adam Langley95c29f32014-06-20 12:00:00 -0700935 if err != nil {
936 c.sendAlert(alertUnexpectedMessage)
937 return err
938 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400939 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
940 c.curveID = ecdhe.curveID
941 }
Adam Langley95c29f32014-06-20 12:00:00 -0700942
Nick Harper60edffd2016-06-21 15:19:24 -0700943 c.peerSignatureAlgorithm = keyAgreement.peerSignatureAlgorithm()
944
Adam Langley95c29f32014-06-20 12:00:00 -0700945 msg, err = c.readHandshake()
946 if err != nil {
947 return err
948 }
949 }
950
951 var chainToSend *Certificate
952 var certRequested bool
953 certReq, ok := msg.(*certificateRequestMsg)
954 if ok {
955 certRequested = true
David Benjamin7a41d372016-07-09 11:21:54 -0700956 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
957 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
958 }
Adam Langley95c29f32014-06-20 12:00:00 -0700959
David Benjamin83c0bc92014-08-04 01:23:53 -0400960 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700961
David Benjamina6f82632016-07-01 18:44:02 -0400962 chainToSend, err = selectClientCertificate(c, certReq)
963 if err != nil {
964 return err
Adam Langley95c29f32014-06-20 12:00:00 -0700965 }
966
967 msg, err = c.readHandshake()
968 if err != nil {
969 return err
970 }
971 }
972
973 shd, ok := msg.(*serverHelloDoneMsg)
974 if !ok {
975 c.sendAlert(alertUnexpectedMessage)
976 return unexpectedMessageError(shd, msg)
977 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400978 hs.writeServerHash(shd.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700979
980 // If the server requested a certificate then we have to send a
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500981 // Certificate message in TLS, even if it's empty because we don't have
982 // a certificate to send. In SSL 3.0, skip the message and send a
983 // no_certificate warning alert.
Adam Langley95c29f32014-06-20 12:00:00 -0700984 if certRequested {
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500985 if c.vers == VersionSSL30 && chainToSend == nil {
986 c.sendAlert(alertNoCertficate)
987 } else if !c.config.Bugs.SkipClientCertificate {
988 certMsg := new(certificateMsg)
989 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -0400990 for _, certData := range chainToSend.Certificate {
991 certMsg.certificates = append(certMsg.certificates, certificateEntry{
992 data: certData,
993 })
994 }
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500995 }
996 hs.writeClientHash(certMsg.marshal())
997 c.writeRecord(recordTypeHandshake, certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700998 }
Adam Langley95c29f32014-06-20 12:00:00 -0700999 }
1000
David Benjamin48cae082014-10-27 01:06:24 -04001001 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, leaf)
Adam Langley95c29f32014-06-20 12:00:00 -07001002 if err != nil {
1003 c.sendAlert(alertInternalError)
1004 return err
1005 }
1006 if ckx != nil {
David Benjaminf3ec83d2014-07-21 22:42:34 -04001007 if c.config.Bugs.EarlyChangeCipherSpec < 2 {
David Benjamin83c0bc92014-08-04 01:23:53 -04001008 hs.writeClientHash(ckx.marshal())
David Benjaminf3ec83d2014-07-21 22:42:34 -04001009 }
Adam Langley95c29f32014-06-20 12:00:00 -07001010 c.writeRecord(recordTypeHandshake, ckx.marshal())
1011 }
1012
Nick Harperb3d51be2016-07-01 11:43:18 -04001013 if hs.serverHello.extensions.extendedMasterSecret && c.vers >= VersionTLS10 {
Adam Langley75712922014-10-10 16:23:43 -07001014 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1015 c.extendedMasterSecret = true
1016 } else {
1017 if c.config.Bugs.RequireExtendedMasterSecret {
1018 return errors.New("tls: extended master secret required but not supported by peer")
1019 }
1020 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
1021 }
David Benjamine098ec22014-08-27 23:13:20 -04001022
Adam Langley95c29f32014-06-20 12:00:00 -07001023 if chainToSend != nil {
Adam Langley95c29f32014-06-20 12:00:00 -07001024 certVerify := &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001025 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001026 }
1027
David Benjamin72dc7832015-03-16 17:49:43 -04001028 // Determine the hash to sign.
Nick Harper60edffd2016-06-21 15:19:24 -07001029 privKey := c.config.Certificates[0].PrivateKey
David Benjamin72dc7832015-03-16 17:49:43 -04001030
Nick Harper60edffd2016-06-21 15:19:24 -07001031 if certVerify.hasSignatureAlgorithm {
David Benjamin0a8deb22016-07-09 21:02:01 -07001032 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
Nick Harper60edffd2016-06-21 15:19:24 -07001033 if err != nil {
1034 c.sendAlert(alertInternalError)
1035 return err
Adam Langley95c29f32014-06-20 12:00:00 -07001036 }
Nick Harper60edffd2016-06-21 15:19:24 -07001037 }
1038
1039 if c.vers > VersionSSL30 {
David Benjamin5208fd42016-07-13 21:43:25 -04001040 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, hs.finishedHash.buffer)
David Benjamina95e9f32016-07-08 16:28:04 -07001041 if err == nil && c.config.Bugs.SendSignatureAlgorithm != 0 {
1042 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
1043 }
Nick Harper60edffd2016-06-21 15:19:24 -07001044 } else {
1045 // SSL 3.0's client certificate construction is
1046 // incompatible with signatureAlgorithm.
1047 rsaKey, ok := privKey.(*rsa.PrivateKey)
1048 if !ok {
1049 err = errors.New("unsupported signature type for client certificate")
1050 } else {
1051 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
David Benjamin5208fd42016-07-13 21:43:25 -04001052 if c.config.Bugs.InvalidSignature {
Nick Harper60edffd2016-06-21 15:19:24 -07001053 digest[0] ^= 0x80
1054 }
1055 certVerify.signature, err = rsa.SignPKCS1v15(c.config.rand(), rsaKey, crypto.MD5SHA1, digest)
1056 }
Adam Langley95c29f32014-06-20 12:00:00 -07001057 }
1058 if err != nil {
1059 c.sendAlert(alertInternalError)
1060 return errors.New("tls: failed to sign handshake with client certificate: " + err.Error())
1061 }
Adam Langley95c29f32014-06-20 12:00:00 -07001062
David Benjamin83c0bc92014-08-04 01:23:53 -04001063 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001064 c.writeRecord(recordTypeHandshake, certVerify.marshal())
1065 }
David Benjamin82261be2016-07-07 14:32:50 -07001066 // flushHandshake will be called in sendFinished.
Adam Langley95c29f32014-06-20 12:00:00 -07001067
David Benjamine098ec22014-08-27 23:13:20 -04001068 hs.finishedHash.discardHandshakeBuffer()
1069
Adam Langley95c29f32014-06-20 12:00:00 -07001070 return nil
1071}
1072
David Benjamin75051442016-07-01 18:58:51 -04001073func (hs *clientHandshakeState) verifyCertificates(certMsg *certificateMsg) error {
1074 c := hs.c
1075
1076 if len(certMsg.certificates) == 0 {
1077 c.sendAlert(alertIllegalParameter)
1078 return errors.New("tls: no certificates sent")
1079 }
1080
1081 certs := make([]*x509.Certificate, len(certMsg.certificates))
Steven Valdeza833c352016-11-01 13:39:36 -04001082 for i, certEntry := range certMsg.certificates {
1083 cert, err := x509.ParseCertificate(certEntry.data)
David Benjamin75051442016-07-01 18:58:51 -04001084 if err != nil {
1085 c.sendAlert(alertBadCertificate)
1086 return errors.New("tls: failed to parse certificate from server: " + err.Error())
1087 }
1088 certs[i] = cert
1089 }
1090
1091 if !c.config.InsecureSkipVerify {
1092 opts := x509.VerifyOptions{
1093 Roots: c.config.RootCAs,
1094 CurrentTime: c.config.time(),
1095 DNSName: c.config.ServerName,
1096 Intermediates: x509.NewCertPool(),
1097 }
1098
1099 for i, cert := range certs {
1100 if i == 0 {
1101 continue
1102 }
1103 opts.Intermediates.AddCert(cert)
1104 }
1105 var err error
1106 c.verifiedChains, err = certs[0].Verify(opts)
1107 if err != nil {
1108 c.sendAlert(alertBadCertificate)
1109 return err
1110 }
1111 }
1112
1113 switch certs[0].PublicKey.(type) {
1114 case *rsa.PublicKey, *ecdsa.PublicKey:
1115 break
1116 default:
1117 c.sendAlert(alertUnsupportedCertificate)
1118 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
1119 }
1120
1121 c.peerCertificates = certs
1122 return nil
1123}
1124
Adam Langley95c29f32014-06-20 12:00:00 -07001125func (hs *clientHandshakeState) establishKeys() error {
1126 c := hs.c
1127
1128 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001129 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 -07001130 var clientCipher, serverCipher interface{}
1131 var clientHash, serverHash macFunction
1132 if hs.suite.cipher != nil {
1133 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
1134 clientHash = hs.suite.mac(c.vers, clientMAC)
1135 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
1136 serverHash = hs.suite.mac(c.vers, serverMAC)
1137 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001138 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1139 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001140 }
1141
1142 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
1143 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
1144 return nil
1145}
1146
David Benjamin75101402016-07-01 13:40:23 -04001147func (hs *clientHandshakeState) processServerExtensions(serverExtensions *serverExtensions) error {
1148 c := hs.c
1149
David Benjamin8d315d72016-07-18 01:03:18 +02001150 if c.vers < VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001151 if c.config.Bugs.RequireRenegotiationInfo && serverExtensions.secureRenegotiation == nil {
1152 return errors.New("tls: renegotiation extension missing")
1153 }
David Benjamin75101402016-07-01 13:40:23 -04001154
Nick Harperb41d2e42016-07-01 17:50:32 -04001155 if len(c.clientVerify) > 0 && !c.noRenegotiationInfo() {
1156 var expectedRenegInfo []byte
1157 expectedRenegInfo = append(expectedRenegInfo, c.clientVerify...)
1158 expectedRenegInfo = append(expectedRenegInfo, c.serverVerify...)
1159 if !bytes.Equal(serverExtensions.secureRenegotiation, expectedRenegInfo) {
1160 c.sendAlert(alertHandshakeFailure)
1161 return fmt.Errorf("tls: renegotiation mismatch")
1162 }
David Benjamin75101402016-07-01 13:40:23 -04001163 }
David Benjamincea0ab42016-07-14 12:33:14 -04001164 } else if serverExtensions.secureRenegotiation != nil {
1165 return errors.New("tls: renegotiation info sent in TLS 1.3")
David Benjamin75101402016-07-01 13:40:23 -04001166 }
1167
1168 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
1169 if serverExtensions.customExtension != *expected {
1170 return fmt.Errorf("tls: bad custom extension contents %q", serverExtensions.customExtension)
1171 }
1172 }
1173
1174 clientDidNPN := hs.hello.nextProtoNeg
1175 clientDidALPN := len(hs.hello.alpnProtocols) > 0
1176 serverHasNPN := serverExtensions.nextProtoNeg
1177 serverHasALPN := len(serverExtensions.alpnProtocol) > 0
1178
1179 if !clientDidNPN && serverHasNPN {
1180 c.sendAlert(alertHandshakeFailure)
1181 return errors.New("server advertised unrequested NPN extension")
1182 }
1183
1184 if !clientDidALPN && serverHasALPN {
1185 c.sendAlert(alertHandshakeFailure)
1186 return errors.New("server advertised unrequested ALPN extension")
1187 }
1188
1189 if serverHasNPN && serverHasALPN {
1190 c.sendAlert(alertHandshakeFailure)
1191 return errors.New("server advertised both NPN and ALPN extensions")
1192 }
1193
1194 if serverHasALPN {
1195 c.clientProtocol = serverExtensions.alpnProtocol
1196 c.clientProtocolFallback = false
1197 c.usedALPN = true
1198 }
1199
David Benjamin8d315d72016-07-18 01:03:18 +02001200 if serverHasNPN && c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001201 c.sendAlert(alertHandshakeFailure)
1202 return errors.New("server advertised NPN over TLS 1.3")
1203 }
1204
David Benjamin75101402016-07-01 13:40:23 -04001205 if !hs.hello.channelIDSupported && serverExtensions.channelIDRequested {
1206 c.sendAlert(alertHandshakeFailure)
1207 return errors.New("server advertised unrequested Channel ID extension")
1208 }
1209
David Benjamin8d315d72016-07-18 01:03:18 +02001210 if serverExtensions.extendedMasterSecret && c.vers >= VersionTLS13 {
David Benjamine9077652016-07-13 21:02:08 -04001211 return errors.New("tls: server advertised extended master secret over TLS 1.3")
1212 }
1213
David Benjamin8d315d72016-07-18 01:03:18 +02001214 if serverExtensions.ticketSupported && c.vers >= VersionTLS13 {
Steven Valdez143e8b32016-07-11 13:19:03 -04001215 return errors.New("tls: server advertised ticket extension over TLS 1.3")
1216 }
1217
Steven Valdeza833c352016-11-01 13:39:36 -04001218 if serverExtensions.ocspStapling && c.vers >= VersionTLS13 {
1219 return errors.New("tls: server advertised OCSP in ServerHello over TLS 1.3")
1220 }
1221
David Benjamin53210cb2016-11-16 09:01:48 +09001222 if serverExtensions.ocspStapling && c.config.Bugs.NoOCSPStapling {
1223 return errors.New("tls: server advertised unrequested OCSP extension")
1224 }
1225
Steven Valdeza833c352016-11-01 13:39:36 -04001226 if len(serverExtensions.sctList) > 0 && c.vers >= VersionTLS13 {
1227 return errors.New("tls: server advertised SCTs in ServerHello over TLS 1.3")
1228 }
1229
David Benjamin53210cb2016-11-16 09:01:48 +09001230 if len(serverExtensions.sctList) > 0 && c.config.Bugs.NoSignedCertificateTimestamps {
1231 return errors.New("tls: server advertised unrequested SCTs")
1232 }
1233
David Benjamin75101402016-07-01 13:40:23 -04001234 if serverExtensions.srtpProtectionProfile != 0 {
1235 if serverExtensions.srtpMasterKeyIdentifier != "" {
1236 return errors.New("tls: server selected SRTP MKI value")
1237 }
1238
1239 found := false
1240 for _, p := range c.config.SRTPProtectionProfiles {
1241 if p == serverExtensions.srtpProtectionProfile {
1242 found = true
1243 break
1244 }
1245 }
1246 if !found {
1247 return errors.New("tls: server advertised unsupported SRTP profile")
1248 }
1249
1250 c.srtpProtectionProfile = serverExtensions.srtpProtectionProfile
1251 }
1252
1253 return nil
1254}
1255
Adam Langley95c29f32014-06-20 12:00:00 -07001256func (hs *clientHandshakeState) serverResumedSession() bool {
1257 // If the server responded with the same sessionId then it means the
1258 // sessionTicket is being used to resume a TLS session.
1259 return hs.session != nil && hs.hello.sessionId != nil &&
1260 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
1261}
1262
1263func (hs *clientHandshakeState) processServerHello() (bool, error) {
1264 c := hs.c
1265
Adam Langley95c29f32014-06-20 12:00:00 -07001266 if hs.serverResumedSession() {
David Benjamin4b27d9f2015-05-12 22:42:52 -04001267 // For test purposes, assert that the server never accepts the
1268 // resumption offer on renegotiation.
1269 if c.cipherSuite != nil && c.config.Bugs.FailIfResumeOnRenego {
1270 return false, errors.New("tls: server resumed session on renegotiation")
1271 }
1272
Nick Harperb3d51be2016-07-01 11:43:18 -04001273 if hs.serverHello.extensions.sctList != nil {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001274 return false, errors.New("tls: server sent SCT extension on session resumption")
1275 }
1276
Nick Harperb3d51be2016-07-01 11:43:18 -04001277 if hs.serverHello.extensions.ocspStapling {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001278 return false, errors.New("tls: server sent OCSP extension on session resumption")
1279 }
1280
Adam Langley95c29f32014-06-20 12:00:00 -07001281 // Restore masterSecret and peerCerts from previous state
1282 hs.masterSecret = hs.session.masterSecret
1283 c.peerCertificates = hs.session.serverCertificates
Adam Langley75712922014-10-10 16:23:43 -07001284 c.extendedMasterSecret = hs.session.extendedMasterSecret
Paul Lietar62be8ac2015-09-16 10:03:30 +01001285 c.sctList = hs.session.sctList
1286 c.ocspResponse = hs.session.ocspResponse
David Benjamine098ec22014-08-27 23:13:20 -04001287 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001288 return true, nil
1289 }
Paul Lietar62be8ac2015-09-16 10:03:30 +01001290
Nick Harperb3d51be2016-07-01 11:43:18 -04001291 if hs.serverHello.extensions.sctList != nil {
1292 c.sctList = hs.serverHello.extensions.sctList
Paul Lietar62be8ac2015-09-16 10:03:30 +01001293 }
1294
Adam Langley95c29f32014-06-20 12:00:00 -07001295 return false, nil
1296}
1297
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001298func (hs *clientHandshakeState) readFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001299 c := hs.c
1300
1301 c.readRecord(recordTypeChangeCipherSpec)
1302 if err := c.in.error(); err != nil {
1303 return err
1304 }
1305
1306 msg, err := c.readHandshake()
1307 if err != nil {
1308 return err
1309 }
1310 serverFinished, ok := msg.(*finishedMsg)
1311 if !ok {
1312 c.sendAlert(alertUnexpectedMessage)
1313 return unexpectedMessageError(serverFinished, msg)
1314 }
1315
David Benjaminf3ec83d2014-07-21 22:42:34 -04001316 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
1317 verify := hs.finishedHash.serverSum(hs.masterSecret)
1318 if len(verify) != len(serverFinished.verifyData) ||
1319 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
1320 c.sendAlert(alertHandshakeFailure)
1321 return errors.New("tls: server's Finished message was incorrect")
1322 }
Adam Langley95c29f32014-06-20 12:00:00 -07001323 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001324 c.serverVerify = append(c.serverVerify[:0], serverFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001325 copy(out, serverFinished.verifyData)
David Benjamin83c0bc92014-08-04 01:23:53 -04001326 hs.writeServerHash(serverFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001327 return nil
1328}
1329
1330func (hs *clientHandshakeState) readSessionTicket() error {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001331 c := hs.c
1332
1333 // Create a session with no server identifier. Either a
1334 // session ID or session ticket will be attached.
1335 session := &ClientSessionState{
1336 vers: c.vers,
1337 cipherSuite: hs.suite.id,
1338 masterSecret: hs.masterSecret,
Nick Harperc9846112016-10-17 15:05:35 -07001339 handshakeHash: hs.finishedHash.Sum(),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001340 serverCertificates: c.peerCertificates,
Paul Lietar62be8ac2015-09-16 10:03:30 +01001341 sctList: c.sctList,
1342 ocspResponse: c.ocspResponse,
Nick Harper0b3625b2016-07-25 16:16:28 -07001343 ticketExpiration: c.config.time().Add(time.Duration(7 * 24 * time.Hour)),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001344 }
1345
Nick Harperb3d51be2016-07-01 11:43:18 -04001346 if !hs.serverHello.extensions.ticketSupported {
David Benjamind98452d2015-06-16 14:16:23 -04001347 if c.config.Bugs.ExpectNewTicket {
1348 return errors.New("tls: expected new ticket")
1349 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001350 if hs.session == nil && len(hs.serverHello.sessionId) > 0 {
1351 session.sessionId = hs.serverHello.sessionId
1352 hs.session = session
1353 }
Adam Langley95c29f32014-06-20 12:00:00 -07001354 return nil
1355 }
1356
David Benjaminc7ce9772015-10-09 19:32:41 -04001357 if c.vers == VersionSSL30 {
1358 return errors.New("tls: negotiated session tickets in SSL 3.0")
1359 }
1360
Adam Langley95c29f32014-06-20 12:00:00 -07001361 msg, err := c.readHandshake()
1362 if err != nil {
1363 return err
1364 }
1365 sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
1366 if !ok {
1367 c.sendAlert(alertUnexpectedMessage)
1368 return unexpectedMessageError(sessionTicketMsg, msg)
1369 }
Adam Langley95c29f32014-06-20 12:00:00 -07001370
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001371 session.sessionTicket = sessionTicketMsg.ticket
1372 hs.session = session
Adam Langley95c29f32014-06-20 12:00:00 -07001373
David Benjamind30a9902014-08-24 01:44:23 -04001374 hs.writeServerHash(sessionTicketMsg.marshal())
1375
Adam Langley95c29f32014-06-20 12:00:00 -07001376 return nil
1377}
1378
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001379func (hs *clientHandshakeState) sendFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001380 c := hs.c
1381
David Benjamin0b8d5da2016-07-15 00:39:56 -04001382 var postCCSMsgs [][]byte
David Benjamin83c0bc92014-08-04 01:23:53 -04001383 seqno := hs.c.sendHandshakeSeq
Nick Harperb3d51be2016-07-01 11:43:18 -04001384 if hs.serverHello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001385 nextProto := new(nextProtoMsg)
Nick Harperb3d51be2016-07-01 11:43:18 -04001386 proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.extensions.nextProtos)
Adam Langley95c29f32014-06-20 12:00:00 -07001387 nextProto.proto = proto
1388 c.clientProtocol = proto
1389 c.clientProtocolFallback = fallback
1390
David Benjamin86271ee2014-07-21 16:14:03 -04001391 nextProtoBytes := nextProto.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -04001392 hs.writeHash(nextProtoBytes, seqno)
1393 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001394 postCCSMsgs = append(postCCSMsgs, nextProtoBytes)
Adam Langley95c29f32014-06-20 12:00:00 -07001395 }
1396
Nick Harperb3d51be2016-07-01 11:43:18 -04001397 if hs.serverHello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001398 var resumeHash []byte
1399 if isResume {
1400 resumeHash = hs.session.handshakeHash
1401 }
Nick Harper60a85cb2016-09-23 16:25:11 -07001402 channelIDMsgBytes, err := hs.writeChannelIDMessage(hs.finishedHash.hashForChannelID(resumeHash))
David Benjamind30a9902014-08-24 01:44:23 -04001403 if err != nil {
1404 return err
1405 }
David Benjamin24599a82016-06-30 18:56:53 -04001406 hs.writeHash(channelIDMsgBytes, seqno)
David Benjamind30a9902014-08-24 01:44:23 -04001407 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001408 postCCSMsgs = append(postCCSMsgs, channelIDMsgBytes)
David Benjamind30a9902014-08-24 01:44:23 -04001409 }
1410
Adam Langley95c29f32014-06-20 12:00:00 -07001411 finished := new(finishedMsg)
David Benjaminf3ec83d2014-07-21 22:42:34 -04001412 if c.config.Bugs.EarlyChangeCipherSpec == 2 {
1413 finished.verifyData = hs.finishedHash.clientSum(nil)
1414 } else {
1415 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
1416 }
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001417 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001418 if c.config.Bugs.BadFinished {
1419 finished.verifyData[0]++
1420 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001421 c.clientVerify = append(c.clientVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001422 hs.finishedBytes = finished.marshal()
1423 hs.writeHash(hs.finishedBytes, seqno)
David Benjamin0b8d5da2016-07-15 00:39:56 -04001424 postCCSMsgs = append(postCCSMsgs, hs.finishedBytes)
David Benjamin86271ee2014-07-21 16:14:03 -04001425
1426 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001427 c.writeRecord(recordTypeHandshake, postCCSMsgs[0][:5])
1428 postCCSMsgs[0] = postCCSMsgs[0][5:]
David Benjamin61672812016-07-14 23:10:43 -04001429 } else if c.config.Bugs.SendUnencryptedFinished {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001430 c.writeRecord(recordTypeHandshake, postCCSMsgs[0])
1431 postCCSMsgs = postCCSMsgs[1:]
David Benjamin86271ee2014-07-21 16:14:03 -04001432 }
David Benjamin582ba042016-07-07 12:33:25 -07001433 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001434
1435 if !c.config.Bugs.SkipChangeCipherSpec &&
1436 c.config.Bugs.EarlyChangeCipherSpec == 0 {
David Benjamin8411b242015-11-26 12:07:28 -05001437 ccs := []byte{1}
1438 if c.config.Bugs.BadChangeCipherSpec != nil {
1439 ccs = c.config.Bugs.BadChangeCipherSpec
1440 }
1441 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamin86271ee2014-07-21 16:14:03 -04001442 }
1443
David Benjamin4189bd92015-01-25 23:52:39 -05001444 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1445 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1446 }
David Benjamindc3da932015-03-12 15:09:02 -04001447 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1448 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1449 return errors.New("tls: simulating post-CCS alert")
1450 }
David Benjamin4189bd92015-01-25 23:52:39 -05001451
David Benjamin0b8d5da2016-07-15 00:39:56 -04001452 if !c.config.Bugs.SkipFinished {
1453 for _, msg := range postCCSMsgs {
1454 c.writeRecord(recordTypeHandshake, msg)
1455 }
David Benjamin02edcd02016-07-27 17:40:37 -04001456
1457 if c.config.Bugs.SendExtraFinished {
1458 c.writeRecord(recordTypeHandshake, finished.marshal())
1459 }
1460
David Benjamin582ba042016-07-07 12:33:25 -07001461 c.flushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -05001462 }
Adam Langley95c29f32014-06-20 12:00:00 -07001463 return nil
1464}
1465
Nick Harper60a85cb2016-09-23 16:25:11 -07001466func (hs *clientHandshakeState) writeChannelIDMessage(channelIDHash []byte) ([]byte, error) {
1467 c := hs.c
1468 channelIDMsg := new(channelIDMsg)
1469 if c.config.ChannelID.Curve != elliptic.P256() {
1470 return nil, fmt.Errorf("tls: Channel ID is not on P-256.")
1471 }
1472 r, s, err := ecdsa.Sign(c.config.rand(), c.config.ChannelID, channelIDHash)
1473 if err != nil {
1474 return nil, err
1475 }
1476 channelID := make([]byte, 128)
1477 writeIntPadded(channelID[0:32], c.config.ChannelID.X)
1478 writeIntPadded(channelID[32:64], c.config.ChannelID.Y)
1479 writeIntPadded(channelID[64:96], r)
1480 writeIntPadded(channelID[96:128], s)
1481 if c.config.Bugs.InvalidChannelIDSignature {
1482 channelID[64] ^= 1
1483 }
1484 channelIDMsg.channelID = channelID
1485
1486 c.channelID = &c.config.ChannelID.PublicKey
1487
1488 return channelIDMsg.marshal(), nil
1489}
1490
David Benjamin83c0bc92014-08-04 01:23:53 -04001491func (hs *clientHandshakeState) writeClientHash(msg []byte) {
1492 // writeClientHash is called before writeRecord.
1493 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1494}
1495
1496func (hs *clientHandshakeState) writeServerHash(msg []byte) {
1497 // writeServerHash is called after readHandshake.
1498 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1499}
1500
1501func (hs *clientHandshakeState) writeHash(msg []byte, seqno uint16) {
1502 if hs.c.isDTLS {
1503 // This is somewhat hacky. DTLS hashes a slightly different format.
1504 // First, the TLS header.
1505 hs.finishedHash.Write(msg[:4])
1506 // Then the sequence number and reassembled fragment offset (always 0).
1507 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1508 // Then the reassembled fragment (always equal to the message length).
1509 hs.finishedHash.Write(msg[1:4])
1510 // And then the message body.
1511 hs.finishedHash.Write(msg[4:])
1512 } else {
1513 hs.finishedHash.Write(msg)
1514 }
1515}
1516
David Benjamina6f82632016-07-01 18:44:02 -04001517// selectClientCertificate selects a certificate for use with the given
1518// certificate, or none if none match. It may return a particular certificate or
1519// nil on success, or an error on internal error.
1520func selectClientCertificate(c *Conn, certReq *certificateRequestMsg) (*Certificate, error) {
1521 // RFC 4346 on the certificateAuthorities field:
1522 // A list of the distinguished names of acceptable certificate
1523 // authorities. These distinguished names may specify a desired
1524 // distinguished name for a root CA or for a subordinate CA; thus, this
1525 // message can be used to describe both known roots and a desired
1526 // authorization space. If the certificate_authorities list is empty
1527 // then the client MAY send any certificate of the appropriate
1528 // ClientCertificateType, unless there is some external arrangement to
1529 // the contrary.
1530
1531 var rsaAvail, ecdsaAvail bool
Nick Harperb41d2e42016-07-01 17:50:32 -04001532 if !certReq.hasRequestContext {
1533 for _, certType := range certReq.certificateTypes {
1534 switch certType {
1535 case CertTypeRSASign:
1536 rsaAvail = true
1537 case CertTypeECDSASign:
1538 ecdsaAvail = true
1539 }
David Benjamina6f82632016-07-01 18:44:02 -04001540 }
1541 }
1542
1543 // We need to search our list of client certs for one
1544 // where SignatureAlgorithm is RSA and the Issuer is in
1545 // certReq.certificateAuthorities
1546findCert:
1547 for i, chain := range c.config.Certificates {
Nick Harperb41d2e42016-07-01 17:50:32 -04001548 if !certReq.hasRequestContext && !rsaAvail && !ecdsaAvail {
David Benjamina6f82632016-07-01 18:44:02 -04001549 continue
1550 }
1551
1552 // Ensure the private key supports one of the advertised
1553 // signature algorithms.
1554 if certReq.hasSignatureAlgorithm {
David Benjamin0a8deb22016-07-09 21:02:01 -07001555 if _, err := selectSignatureAlgorithm(c.vers, chain.PrivateKey, c.config, certReq.signatureAlgorithms); err != nil {
David Benjamina6f82632016-07-01 18:44:02 -04001556 continue
1557 }
1558 }
1559
1560 for j, cert := range chain.Certificate {
1561 x509Cert := chain.Leaf
1562 // parse the certificate if this isn't the leaf
1563 // node, or if chain.Leaf was nil
1564 if j != 0 || x509Cert == nil {
1565 var err error
1566 if x509Cert, err = x509.ParseCertificate(cert); err != nil {
1567 c.sendAlert(alertInternalError)
1568 return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
1569 }
1570 }
1571
Nick Harperb41d2e42016-07-01 17:50:32 -04001572 if !certReq.hasRequestContext {
1573 switch {
1574 case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
1575 case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
1576 default:
1577 continue findCert
1578 }
David Benjamina6f82632016-07-01 18:44:02 -04001579 }
1580
1581 if len(certReq.certificateAuthorities) == 0 {
1582 // They gave us an empty list, so just take the
1583 // first certificate of valid type from
1584 // c.config.Certificates.
1585 return &chain, nil
1586 }
1587
1588 for _, ca := range certReq.certificateAuthorities {
1589 if bytes.Equal(x509Cert.RawIssuer, ca) {
1590 return &chain, nil
1591 }
1592 }
1593 }
1594 }
1595
1596 return nil, nil
1597}
1598
Adam Langley95c29f32014-06-20 12:00:00 -07001599// clientSessionCacheKey returns a key used to cache sessionTickets that could
1600// be used to resume previously negotiated TLS sessions with a server.
1601func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
1602 if len(config.ServerName) > 0 {
1603 return config.ServerName
1604 }
1605 return serverAddr.String()
1606}
1607
David Benjaminfa055a22014-09-15 16:51:51 -04001608// mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
1609// given list of possible protocols and a list of the preference order. The
1610// first list must not be empty. It returns the resulting protocol and flag
Adam Langley95c29f32014-06-20 12:00:00 -07001611// indicating if the fallback case was reached.
David Benjaminfa055a22014-09-15 16:51:51 -04001612func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
1613 for _, s := range preferenceProtos {
1614 for _, c := range protos {
Adam Langley95c29f32014-06-20 12:00:00 -07001615 if s == c {
1616 return s, false
1617 }
1618 }
1619 }
1620
David Benjaminfa055a22014-09-15 16:51:51 -04001621 return protos[0], true
Adam Langley95c29f32014-06-20 12:00:00 -07001622}
David Benjamind30a9902014-08-24 01:44:23 -04001623
1624// writeIntPadded writes x into b, padded up with leading zeros as
1625// needed.
1626func writeIntPadded(b []byte, x *big.Int) {
1627 for i := range b {
1628 b[i] = 0
1629 }
1630 xb := x.Bytes()
1631 copy(b[len(b)-len(xb):], xb)
1632}
Steven Valdeza833c352016-11-01 13:39:36 -04001633
1634func generatePSKBinders(hello *clientHelloMsg, pskCipherSuite *cipherSuite, psk, transcript []byte, config *Config) {
1635 if config.Bugs.SendNoPSKBinder {
1636 return
1637 }
1638
1639 binderLen := pskCipherSuite.hash().Size()
1640 if config.Bugs.SendShortPSKBinder {
1641 binderLen--
1642 }
1643
1644 // Fill hello.pskBinders with appropriate length arrays of zeros so the
1645 // length prefixes are correct when computing the binder over the truncated
1646 // ClientHello message.
1647 hello.pskBinders = make([][]byte, len(hello.pskIdentities))
1648 for i := range hello.pskIdentities {
1649 hello.pskBinders[i] = make([]byte, binderLen)
1650 }
1651
1652 helloBytes := hello.marshal()
1653 binderSize := len(hello.pskBinders)*(binderLen+1) + 2
1654 truncatedHello := helloBytes[:len(helloBytes)-binderSize]
1655 binder := computePSKBinder(psk, resumptionPSKBinderLabel, pskCipherSuite, transcript, truncatedHello)
1656 if config.Bugs.SendShortPSKBinder {
1657 binder = binder[:binderLen]
1658 }
1659 if config.Bugs.SendInvalidPSKBinder {
1660 binder[0] ^= 1
1661 }
1662
1663 for i := range hello.pskBinders {
1664 hello.pskBinders[i] = binder
1665 }
1666
1667 hello.raw = nil
1668}