blob: 3f377f30b20f16acb7657dd51d7d43e8c472c166 [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),
67 ocspStapling: true,
Paul Lietar4fac72e2015-09-09 13:44:55 +010068 sctListSupported: true,
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 Benjamind86c7672014-08-02 04:07:12 -0400312 var helloBytes []byte
313 if c.config.Bugs.SendV2ClientHello {
David Benjamin94d701b2014-11-30 13:54:41 -0500314 // Test that the peer left-pads random.
315 hello.random[0] = 0
David Benjamind86c7672014-08-02 04:07:12 -0400316 v2Hello := &v2ClientHelloMsg{
317 vers: hello.vers,
318 cipherSuites: hello.cipherSuites,
319 // No session resumption for V2ClientHello.
320 sessionId: nil,
David Benjamin94d701b2014-11-30 13:54:41 -0500321 challenge: hello.random[1:],
David Benjamind86c7672014-08-02 04:07:12 -0400322 }
323 helloBytes = v2Hello.marshal()
324 c.writeV2Record(helloBytes)
325 } else {
Steven Valdeza833c352016-11-01 13:39:36 -0400326 if len(hello.pskIdentities) > 0 {
327 generatePSKBinders(hello, pskCipherSuite, session.masterSecret, []byte{}, c.config)
328 }
David Benjamind86c7672014-08-02 04:07:12 -0400329 helloBytes = hello.marshal()
Steven Valdeza833c352016-11-01 13:39:36 -0400330
David Benjamin7964b182016-07-14 23:36:30 -0400331 if c.config.Bugs.PartialClientFinishedWithClientHello {
332 // Include one byte of Finished. We can compute it
333 // without completing the handshake. This assumes we
334 // negotiate TLS 1.3 with no HelloRetryRequest or
335 // CertificateRequest.
336 toWrite := make([]byte, 0, len(helloBytes)+1)
337 toWrite = append(toWrite, helloBytes...)
338 toWrite = append(toWrite, typeFinished)
339 c.writeRecord(recordTypeHandshake, toWrite)
340 } else {
341 c.writeRecord(recordTypeHandshake, helloBytes)
342 }
David Benjamind86c7672014-08-02 04:07:12 -0400343 }
David Benjamin582ba042016-07-07 12:33:25 -0700344 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700345
David Benjamin83f90402015-01-27 01:09:43 -0500346 if err := c.simulatePacketLoss(nil); err != nil {
347 return err
348 }
Adam Langley95c29f32014-06-20 12:00:00 -0700349 msg, err := c.readHandshake()
350 if err != nil {
351 return err
352 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400353
354 if c.isDTLS {
355 helloVerifyRequest, ok := msg.(*helloVerifyRequestMsg)
356 if ok {
David Benjaminda4789e2016-10-31 19:23:34 -0400357 if helloVerifyRequest.vers != versionToWire(VersionTLS10, c.isDTLS) {
David Benjamin8bc38f52014-08-16 12:07:27 -0400358 // Per RFC 6347, the version field in
359 // HelloVerifyRequest SHOULD be always DTLS
360 // 1.0. Enforce this for testing purposes.
361 return errors.New("dtls: bad HelloVerifyRequest version")
362 }
363
David Benjamin83c0bc92014-08-04 01:23:53 -0400364 hello.raw = nil
365 hello.cookie = helloVerifyRequest.cookie
366 helloBytes = hello.marshal()
367 c.writeRecord(recordTypeHandshake, helloBytes)
David Benjamin582ba042016-07-07 12:33:25 -0700368 c.flushHandshake()
David Benjamin83c0bc92014-08-04 01:23:53 -0400369
David Benjamin83f90402015-01-27 01:09:43 -0500370 if err := c.simulatePacketLoss(nil); err != nil {
371 return err
372 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400373 msg, err = c.readHandshake()
374 if err != nil {
375 return err
376 }
377 }
378 }
379
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400380 var serverWireVersion uint16
Nick Harperdcfbc672016-07-16 17:47:31 +0200381 switch m := msg.(type) {
382 case *helloRetryRequestMsg:
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400383 serverWireVersion = m.vers
Nick Harperdcfbc672016-07-16 17:47:31 +0200384 case *serverHelloMsg:
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400385 serverWireVersion = m.vers
Nick Harperdcfbc672016-07-16 17:47:31 +0200386 default:
387 c.sendAlert(alertUnexpectedMessage)
388 return fmt.Errorf("tls: received unexpected message of type %T when waiting for HelloRetryRequest or ServerHello", msg)
389 }
390
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400391 serverVersion, ok := wireToVersion(serverWireVersion, c.isDTLS)
392 if ok {
Steven Valdezfdd10992016-09-15 16:27:05 -0400393 ok = c.config.isSupportedVersion(serverVersion, c.isDTLS)
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400394 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200395 if !ok {
396 c.sendAlert(alertProtocolVersion)
397 return fmt.Errorf("tls: server selected unsupported protocol version %x", c.vers)
398 }
Steven Valdezfdd10992016-09-15 16:27:05 -0400399 c.vers = serverVersion
Nick Harperdcfbc672016-07-16 17:47:31 +0200400 c.haveVers = true
401
402 helloRetryRequest, haveHelloRetryRequest := msg.(*helloRetryRequestMsg)
403 var secondHelloBytes []byte
404 if haveHelloRetryRequest {
David Benjamin3baa6e12016-10-07 21:10:38 -0400405 if len(helloRetryRequest.cookie) > 0 {
406 hello.tls13Cookie = helloRetryRequest.cookie
407 }
408
Steven Valdez5440fe02016-07-18 12:40:30 -0400409 if c.config.Bugs.MisinterpretHelloRetryRequestCurve != 0 {
David Benjamin3baa6e12016-10-07 21:10:38 -0400410 helloRetryRequest.hasSelectedGroup = true
Steven Valdez5440fe02016-07-18 12:40:30 -0400411 helloRetryRequest.selectedGroup = c.config.Bugs.MisinterpretHelloRetryRequestCurve
412 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400413 if helloRetryRequest.hasSelectedGroup {
414 var hrrCurveFound bool
415 group := helloRetryRequest.selectedGroup
416 for _, curveID := range hello.supportedCurves {
417 if group == curveID {
418 hrrCurveFound = true
419 break
420 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200421 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400422 if !hrrCurveFound || keyShares[group] != nil {
423 c.sendAlert(alertHandshakeFailure)
424 return errors.New("tls: received invalid HelloRetryRequest")
425 }
426 curve, ok := curveForCurveID(group)
427 if !ok {
428 return errors.New("tls: Unable to get curve requested in HelloRetryRequest")
429 }
430 publicKey, err := curve.offer(c.config.rand())
431 if err != nil {
432 return err
433 }
434 keyShares[group] = curve
Steven Valdeza833c352016-11-01 13:39:36 -0400435 hello.keyShares = []keyShareEntry{{
David Benjamin3baa6e12016-10-07 21:10:38 -0400436 group: group,
437 keyExchange: publicKey,
Steven Valdeza833c352016-11-01 13:39:36 -0400438 }}
Nick Harperdcfbc672016-07-16 17:47:31 +0200439 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200440
Steven Valdez5440fe02016-07-18 12:40:30 -0400441 if c.config.Bugs.SecondClientHelloMissingKeyShare {
442 hello.hasKeyShares = false
443 }
444
Nick Harperdcfbc672016-07-16 17:47:31 +0200445 hello.hasEarlyData = false
Nick Harperdcfbc672016-07-16 17:47:31 +0200446 hello.raw = nil
447
Steven Valdeza833c352016-11-01 13:39:36 -0400448 if len(hello.pskIdentities) > 0 {
449 generatePSKBinders(hello, pskCipherSuite, session.masterSecret, append(helloBytes, helloRetryRequest.marshal()...), c.config)
450 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200451 secondHelloBytes = hello.marshal()
452 c.writeRecord(recordTypeHandshake, secondHelloBytes)
453 c.flushHandshake()
454
455 msg, err = c.readHandshake()
456 if err != nil {
457 return err
458 }
459 }
460
Adam Langley95c29f32014-06-20 12:00:00 -0700461 serverHello, ok := msg.(*serverHelloMsg)
462 if !ok {
463 c.sendAlert(alertUnexpectedMessage)
464 return unexpectedMessageError(serverHello, msg)
465 }
466
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400467 if serverWireVersion != serverHello.vers {
Adam Langley95c29f32014-06-20 12:00:00 -0700468 c.sendAlert(alertProtocolVersion)
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400469 return fmt.Errorf("tls: server sent non-matching version %x vs %x", serverWireVersion, serverHello.vers)
Adam Langley95c29f32014-06-20 12:00:00 -0700470 }
Adam Langley95c29f32014-06-20 12:00:00 -0700471
Nick Harper85f20c22016-07-04 10:11:59 -0700472 // Check for downgrade signals in the server random, per
David Benjamina128a552016-10-13 14:26:33 -0400473 // draft-ietf-tls-tls13-16, section 4.1.3.
Nick Harper85f20c22016-07-04 10:11:59 -0700474 if c.vers <= VersionTLS12 && c.config.maxVersion(c.isDTLS) >= VersionTLS13 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400475 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS13) {
Nick Harper85f20c22016-07-04 10:11:59 -0700476 c.sendAlert(alertProtocolVersion)
477 return errors.New("tls: downgrade from TLS 1.3 detected")
478 }
479 }
480 if c.vers <= VersionTLS11 && c.config.maxVersion(c.isDTLS) >= VersionTLS12 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400481 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS12) {
Nick Harper85f20c22016-07-04 10:11:59 -0700482 c.sendAlert(alertProtocolVersion)
483 return errors.New("tls: downgrade from TLS 1.2 detected")
484 }
485 }
486
Nick Harper0b3625b2016-07-25 16:16:28 -0700487 suite := mutualCipherSuite(hello.cipherSuites, serverHello.cipherSuite)
Adam Langley95c29f32014-06-20 12:00:00 -0700488 if suite == nil {
489 c.sendAlert(alertHandshakeFailure)
490 return fmt.Errorf("tls: server selected an unsupported cipher suite")
491 }
492
David Benjamin3baa6e12016-10-07 21:10:38 -0400493 if haveHelloRetryRequest && helloRetryRequest.hasSelectedGroup && helloRetryRequest.selectedGroup != serverHello.keyShare.group {
Nick Harperdcfbc672016-07-16 17:47:31 +0200494 c.sendAlert(alertHandshakeFailure)
495 return errors.New("tls: ServerHello parameters did not match HelloRetryRequest")
496 }
497
Adam Langley95c29f32014-06-20 12:00:00 -0700498 hs := &clientHandshakeState{
499 c: c,
500 serverHello: serverHello,
501 hello: hello,
502 suite: suite,
503 finishedHash: newFinishedHash(c.vers, suite),
Nick Harperb41d2e42016-07-01 17:50:32 -0400504 keyShares: keyShares,
Adam Langley95c29f32014-06-20 12:00:00 -0700505 session: session,
506 }
507
David Benjamin83c0bc92014-08-04 01:23:53 -0400508 hs.writeHash(helloBytes, hs.c.sendHandshakeSeq-1)
Nick Harperdcfbc672016-07-16 17:47:31 +0200509 if haveHelloRetryRequest {
510 hs.writeServerHash(helloRetryRequest.marshal())
511 hs.writeClientHash(secondHelloBytes)
512 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400513 hs.writeServerHash(hs.serverHello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700514
David Benjamin8d315d72016-07-18 01:03:18 +0200515 if c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -0400516 if err := hs.doTLS13Handshake(); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700517 return err
518 }
519 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400520 if c.config.Bugs.EarlyChangeCipherSpec > 0 {
521 hs.establishKeys()
522 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
523 }
524
525 if hs.serverHello.compressionMethod != compressionNone {
526 c.sendAlert(alertUnexpectedMessage)
527 return errors.New("tls: server selected unsupported compression format")
528 }
529
530 err = hs.processServerExtensions(&serverHello.extensions)
531 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700532 return err
533 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400534
535 isResume, err := hs.processServerHello()
536 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700537 return err
538 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400539
540 if isResume {
541 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
542 if err := hs.establishKeys(); err != nil {
543 return err
544 }
545 }
546 if err := hs.readSessionTicket(); err != nil {
547 return err
548 }
549 if err := hs.readFinished(c.firstFinished[:]); err != nil {
550 return err
551 }
552 if err := hs.sendFinished(nil, isResume); err != nil {
553 return err
554 }
555 } else {
556 if err := hs.doFullHandshake(); err != nil {
557 return err
558 }
559 if err := hs.establishKeys(); err != nil {
560 return err
561 }
562 if err := hs.sendFinished(c.firstFinished[:], isResume); err != nil {
563 return err
564 }
565 // Most retransmits are triggered by a timeout, but the final
566 // leg of the handshake is retransmited upon re-receiving a
567 // Finished.
568 if err := c.simulatePacketLoss(func() {
David Benjamin02edcd02016-07-27 17:40:37 -0400569 c.sendHandshakeSeq--
Nick Harperb41d2e42016-07-01 17:50:32 -0400570 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
571 c.flushHandshake()
572 }); err != nil {
573 return err
574 }
575 if err := hs.readSessionTicket(); err != nil {
576 return err
577 }
578 if err := hs.readFinished(nil); err != nil {
579 return err
580 }
Adam Langley95c29f32014-06-20 12:00:00 -0700581 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400582
583 if sessionCache != nil && hs.session != nil && session != hs.session {
584 if c.config.Bugs.RequireSessionTickets && len(hs.session.sessionTicket) == 0 {
585 return errors.New("tls: new session used session IDs instead of tickets")
586 }
587 sessionCache.Put(cacheKey, hs.session)
David Benjamin83f90402015-01-27 01:09:43 -0500588 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400589
590 c.didResume = isResume
David Benjamin97a0a082016-07-13 17:57:35 -0400591 c.exporterSecret = hs.masterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700592 }
593
Adam Langley95c29f32014-06-20 12:00:00 -0700594 c.handshakeComplete = true
David Benjaminc565ebb2015-04-03 04:06:36 -0400595 c.cipherSuite = suite
596 copy(c.clientRandom[:], hs.hello.random)
597 copy(c.serverRandom[:], hs.serverHello.random)
Paul Lietar4fac72e2015-09-09 13:44:55 +0100598
Adam Langley95c29f32014-06-20 12:00:00 -0700599 return nil
600}
601
Nick Harperb41d2e42016-07-01 17:50:32 -0400602func (hs *clientHandshakeState) doTLS13Handshake() error {
603 c := hs.c
604
605 // Once the PRF hash is known, TLS 1.3 does not require a handshake
606 // buffer.
607 hs.finishedHash.discardHandshakeBuffer()
608
609 zeroSecret := hs.finishedHash.zeroSecret()
610
611 // Resolve PSK and compute the early secret.
612 //
613 // TODO(davidben): This will need to be handled slightly earlier once
614 // 0-RTT is implemented.
615 var psk []byte
Steven Valdez803c77a2016-09-06 14:13:43 -0400616 if hs.serverHello.hasPSKIdentity {
Nick Harper0b3625b2016-07-25 16:16:28 -0700617 // We send at most one PSK identity.
618 if hs.session == nil || hs.serverHello.pskIdentity != 0 {
619 c.sendAlert(alertUnknownPSKIdentity)
620 return errors.New("tls: server sent unknown PSK identity")
621 }
Steven Valdez803c77a2016-09-06 14:13:43 -0400622 if hs.session.cipherSuite != hs.suite.id {
Nick Harper0b3625b2016-07-25 16:16:28 -0700623 c.sendAlert(alertHandshakeFailure)
Steven Valdez803c77a2016-09-06 14:13:43 -0400624 return errors.New("tls: server sent invalid cipher suite")
Nick Harper0b3625b2016-07-25 16:16:28 -0700625 }
Steven Valdeza833c352016-11-01 13:39:36 -0400626 psk = hs.session.masterSecret
Nick Harper0b3625b2016-07-25 16:16:28 -0700627 c.didResume = true
Nick Harperb41d2e42016-07-01 17:50:32 -0400628 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400629 psk = zeroSecret
Nick Harperb41d2e42016-07-01 17:50:32 -0400630 }
631
632 earlySecret := hs.finishedHash.extractKey(zeroSecret, psk)
633
Steven Valdeza833c352016-11-01 13:39:36 -0400634 if !hs.serverHello.hasKeyShare {
635 c.sendAlert(alertUnsupportedExtension)
636 return errors.New("tls: server omitted KeyShare on resumption.")
637 }
638
Nick Harperb41d2e42016-07-01 17:50:32 -0400639 // Resolve ECDHE and compute the handshake secret.
640 var ecdheSecret []byte
Steven Valdez803c77a2016-09-06 14:13:43 -0400641 if !c.config.Bugs.MissingKeyShare && !c.config.Bugs.SecondClientHelloMissingKeyShare {
Nick Harperb41d2e42016-07-01 17:50:32 -0400642 curve, ok := hs.keyShares[hs.serverHello.keyShare.group]
643 if !ok {
644 c.sendAlert(alertHandshakeFailure)
645 return errors.New("tls: server selected an unsupported group")
646 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400647 c.curveID = hs.serverHello.keyShare.group
Nick Harperb41d2e42016-07-01 17:50:32 -0400648
649 var err error
650 ecdheSecret, err = curve.finish(hs.serverHello.keyShare.keyExchange)
651 if err != nil {
652 return err
653 }
654 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400655 ecdheSecret = zeroSecret
656 }
657
658 // Compute the handshake secret.
659 handshakeSecret := hs.finishedHash.extractKey(earlySecret, ecdheSecret)
660
661 // Switch to handshake traffic keys.
Steven Valdezc4aa7272016-10-03 12:25:56 -0400662 clientHandshakeTrafficSecret := hs.finishedHash.deriveSecret(handshakeSecret, clientHandshakeTrafficLabel)
Steven Valdeza833c352016-11-01 13:39:36 -0400663 c.out.useTrafficSecret(c.vers, hs.suite, clientHandshakeTrafficSecret, clientWrite)
Steven Valdezc4aa7272016-10-03 12:25:56 -0400664 serverHandshakeTrafficSecret := hs.finishedHash.deriveSecret(handshakeSecret, serverHandshakeTrafficLabel)
Steven Valdeza833c352016-11-01 13:39:36 -0400665 c.in.useTrafficSecret(c.vers, hs.suite, serverHandshakeTrafficSecret, serverWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -0400666
667 msg, err := c.readHandshake()
668 if err != nil {
669 return err
670 }
671
672 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
673 if !ok {
674 c.sendAlert(alertUnexpectedMessage)
675 return unexpectedMessageError(encryptedExtensions, msg)
676 }
677 hs.writeServerHash(encryptedExtensions.marshal())
678
679 err = hs.processServerExtensions(&encryptedExtensions.extensions)
680 if err != nil {
681 return err
682 }
683
684 var chainToSend *Certificate
David Benjamin8d343b42016-07-09 14:26:01 -0700685 var certReq *certificateRequestMsg
Steven Valdeza833c352016-11-01 13:39:36 -0400686 if c.didResume {
Nick Harper0b3625b2016-07-25 16:16:28 -0700687 // Copy over authentication from the session.
688 c.peerCertificates = hs.session.serverCertificates
689 c.sctList = hs.session.sctList
690 c.ocspResponse = hs.session.ocspResponse
David Benjamin44b33bc2016-07-01 22:40:23 -0400691 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400692 msg, err := c.readHandshake()
693 if err != nil {
694 return err
695 }
696
David Benjamin8d343b42016-07-09 14:26:01 -0700697 var ok bool
698 certReq, ok = msg.(*certificateRequestMsg)
Nick Harperb41d2e42016-07-01 17:50:32 -0400699 if ok {
David Benjamin8a8349b2016-08-18 02:32:23 -0400700 if len(certReq.requestContext) != 0 {
701 return errors.New("tls: non-empty certificate request context sent in handshake")
702 }
703
David Benjaminb62d2872016-07-18 14:55:02 +0200704 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
705 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
706 }
707
Nick Harperb41d2e42016-07-01 17:50:32 -0400708 hs.writeServerHash(certReq.marshal())
Nick Harperb41d2e42016-07-01 17:50:32 -0400709
710 chainToSend, err = selectClientCertificate(c, certReq)
711 if err != nil {
712 return err
713 }
714
715 msg, err = c.readHandshake()
716 if err != nil {
717 return err
718 }
719 }
720
721 certMsg, ok := msg.(*certificateMsg)
722 if !ok {
723 c.sendAlert(alertUnexpectedMessage)
724 return unexpectedMessageError(certMsg, msg)
725 }
726 hs.writeServerHash(certMsg.marshal())
727
728 if err := hs.verifyCertificates(certMsg); err != nil {
729 return err
730 }
731 leaf := c.peerCertificates[0]
Steven Valdeza833c352016-11-01 13:39:36 -0400732 c.ocspResponse = certMsg.certificates[0].ocspResponse
733 c.sctList = certMsg.certificates[0].sctList
734
735 if c.config.Bugs.ExpectNoExtensionsOnIntermediate {
736 for _, cert := range certMsg.certificates[1:] {
737 if cert.ocspResponse != nil || cert.sctList != nil {
738 c.sendAlert(alertUnsupportedExtension)
739 return errors.New("tls: unexpected extensions in the client certificate")
740 }
741 }
742 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400743
744 msg, err = c.readHandshake()
745 if err != nil {
746 return err
747 }
748 certVerifyMsg, ok := msg.(*certificateVerifyMsg)
749 if !ok {
750 c.sendAlert(alertUnexpectedMessage)
751 return unexpectedMessageError(certVerifyMsg, msg)
752 }
753
David Benjaminf74ec792016-07-13 21:18:49 -0400754 c.peerSignatureAlgorithm = certVerifyMsg.signatureAlgorithm
Nick Harperb41d2e42016-07-01 17:50:32 -0400755 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
David Benjamin1fb125c2016-07-08 18:52:12 -0700756 err = verifyMessage(c.vers, leaf.PublicKey, c.config, certVerifyMsg.signatureAlgorithm, input, certVerifyMsg.signature)
Nick Harperb41d2e42016-07-01 17:50:32 -0400757 if err != nil {
758 return err
759 }
760
761 hs.writeServerHash(certVerifyMsg.marshal())
762 }
763
764 msg, err = c.readHandshake()
765 if err != nil {
766 return err
767 }
768 serverFinished, ok := msg.(*finishedMsg)
769 if !ok {
770 c.sendAlert(alertUnexpectedMessage)
771 return unexpectedMessageError(serverFinished, msg)
772 }
773
Steven Valdezc4aa7272016-10-03 12:25:56 -0400774 verify := hs.finishedHash.serverSum(serverHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400775 if len(verify) != len(serverFinished.verifyData) ||
776 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
777 c.sendAlert(alertHandshakeFailure)
778 return errors.New("tls: server's Finished message was incorrect")
779 }
780
781 hs.writeServerHash(serverFinished.marshal())
782
783 // The various secrets do not incorporate the client's final leg, so
784 // derive them now before updating the handshake context.
785 masterSecret := hs.finishedHash.extractKey(handshakeSecret, zeroSecret)
Steven Valdezc4aa7272016-10-03 12:25:56 -0400786 clientTrafficSecret := hs.finishedHash.deriveSecret(masterSecret, clientApplicationTrafficLabel)
787 serverTrafficSecret := hs.finishedHash.deriveSecret(masterSecret, serverApplicationTrafficLabel)
Nick Harperb41d2e42016-07-01 17:50:32 -0400788
Steven Valdez0ee2e112016-07-15 06:51:15 -0400789 if certReq != nil && !c.config.Bugs.SkipClientCertificate {
David Benjamin8d343b42016-07-09 14:26:01 -0700790 certMsg := &certificateMsg{
791 hasRequestContext: true,
792 requestContext: certReq.requestContext,
793 }
794 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -0400795 for _, certData := range chainToSend.Certificate {
796 certMsg.certificates = append(certMsg.certificates, certificateEntry{
797 data: certData,
798 extraExtension: c.config.Bugs.SendExtensionOnCertificate,
799 })
800 }
David Benjamin8d343b42016-07-09 14:26:01 -0700801 }
802 hs.writeClientHash(certMsg.marshal())
803 c.writeRecord(recordTypeHandshake, certMsg.marshal())
804
805 if chainToSend != nil {
806 certVerify := &certificateVerifyMsg{
807 hasSignatureAlgorithm: true,
808 }
809
810 // Determine the hash to sign.
811 privKey := chainToSend.PrivateKey
812
813 var err error
814 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
815 if err != nil {
816 c.sendAlert(alertInternalError)
817 return err
818 }
819
820 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
821 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
822 if err != nil {
823 c.sendAlert(alertInternalError)
824 return err
825 }
Steven Valdez0ee2e112016-07-15 06:51:15 -0400826 if c.config.Bugs.SendSignatureAlgorithm != 0 {
827 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
828 }
David Benjamin8d343b42016-07-09 14:26:01 -0700829
830 hs.writeClientHash(certVerify.marshal())
831 c.writeRecord(recordTypeHandshake, certVerify.marshal())
832 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400833 }
834
Nick Harper60a85cb2016-09-23 16:25:11 -0700835 if encryptedExtensions.extensions.channelIDRequested {
836 channelIDHash := crypto.SHA256.New()
837 channelIDHash.Write(hs.finishedHash.certificateVerifyInput(channelIDContextTLS13))
838 channelIDMsgBytes, err := hs.writeChannelIDMessage(channelIDHash.Sum(nil))
839 if err != nil {
840 return err
841 }
842 hs.writeClientHash(channelIDMsgBytes)
843 c.writeRecord(recordTypeHandshake, channelIDMsgBytes)
844 }
845
Nick Harperb41d2e42016-07-01 17:50:32 -0400846 // Send a client Finished message.
847 finished := new(finishedMsg)
Steven Valdezc4aa7272016-10-03 12:25:56 -0400848 finished.verifyData = hs.finishedHash.clientSum(clientHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400849 if c.config.Bugs.BadFinished {
850 finished.verifyData[0]++
851 }
David Benjamin97a0a082016-07-13 17:57:35 -0400852 hs.writeClientHash(finished.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400853 if c.config.Bugs.PartialClientFinishedWithClientHello {
854 // The first byte has already been sent.
855 c.writeRecord(recordTypeHandshake, finished.marshal()[1:])
856 } else {
857 c.writeRecord(recordTypeHandshake, finished.marshal())
858 }
David Benjamin02edcd02016-07-27 17:40:37 -0400859 if c.config.Bugs.SendExtraFinished {
860 c.writeRecord(recordTypeHandshake, finished.marshal())
861 }
David Benjaminee51a222016-07-07 18:34:12 -0700862 c.flushHandshake()
Nick Harperb41d2e42016-07-01 17:50:32 -0400863
864 // Switch to application data keys.
Steven Valdeza833c352016-11-01 13:39:36 -0400865 c.out.useTrafficSecret(c.vers, hs.suite, clientTrafficSecret, clientWrite)
866 c.in.useTrafficSecret(c.vers, hs.suite, serverTrafficSecret, serverWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -0400867
David Benjamin97a0a082016-07-13 17:57:35 -0400868 c.exporterSecret = hs.finishedHash.deriveSecret(masterSecret, exporterLabel)
David Benjamind5a4ecb2016-07-18 01:17:13 +0200869 c.resumptionSecret = hs.finishedHash.deriveSecret(masterSecret, resumptionLabel)
Nick Harperb41d2e42016-07-01 17:50:32 -0400870 return nil
871}
872
Adam Langley95c29f32014-06-20 12:00:00 -0700873func (hs *clientHandshakeState) doFullHandshake() error {
874 c := hs.c
875
David Benjamin48cae082014-10-27 01:06:24 -0400876 var leaf *x509.Certificate
877 if hs.suite.flags&suitePSK == 0 {
878 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700879 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700880 return err
881 }
Adam Langley95c29f32014-06-20 12:00:00 -0700882
David Benjamin48cae082014-10-27 01:06:24 -0400883 certMsg, ok := msg.(*certificateMsg)
David Benjamin75051442016-07-01 18:58:51 -0400884 if !ok {
David Benjamin48cae082014-10-27 01:06:24 -0400885 c.sendAlert(alertUnexpectedMessage)
886 return unexpectedMessageError(certMsg, msg)
887 }
888 hs.writeServerHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700889
David Benjamin75051442016-07-01 18:58:51 -0400890 if err := hs.verifyCertificates(certMsg); err != nil {
891 return err
David Benjamin48cae082014-10-27 01:06:24 -0400892 }
David Benjamin75051442016-07-01 18:58:51 -0400893 leaf = c.peerCertificates[0]
David Benjamin48cae082014-10-27 01:06:24 -0400894 }
Adam Langley95c29f32014-06-20 12:00:00 -0700895
Nick Harperb3d51be2016-07-01 11:43:18 -0400896 if hs.serverHello.extensions.ocspStapling {
David Benjamin48cae082014-10-27 01:06:24 -0400897 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700898 if err != nil {
899 return err
900 }
901 cs, ok := msg.(*certificateStatusMsg)
902 if !ok {
903 c.sendAlert(alertUnexpectedMessage)
904 return unexpectedMessageError(cs, msg)
905 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400906 hs.writeServerHash(cs.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700907
908 if cs.statusType == statusTypeOCSP {
909 c.ocspResponse = cs.response
910 }
911 }
912
David Benjamin48cae082014-10-27 01:06:24 -0400913 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700914 if err != nil {
915 return err
916 }
917
918 keyAgreement := hs.suite.ka(c.vers)
919
920 skx, ok := msg.(*serverKeyExchangeMsg)
921 if ok {
David Benjamin83c0bc92014-08-04 01:23:53 -0400922 hs.writeServerHash(skx.marshal())
David Benjamin48cae082014-10-27 01:06:24 -0400923 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, leaf, skx)
Adam Langley95c29f32014-06-20 12:00:00 -0700924 if err != nil {
925 c.sendAlert(alertUnexpectedMessage)
926 return err
927 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400928 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
929 c.curveID = ecdhe.curveID
930 }
Adam Langley95c29f32014-06-20 12:00:00 -0700931
Nick Harper60edffd2016-06-21 15:19:24 -0700932 c.peerSignatureAlgorithm = keyAgreement.peerSignatureAlgorithm()
933
Adam Langley95c29f32014-06-20 12:00:00 -0700934 msg, err = c.readHandshake()
935 if err != nil {
936 return err
937 }
938 }
939
940 var chainToSend *Certificate
941 var certRequested bool
942 certReq, ok := msg.(*certificateRequestMsg)
943 if ok {
944 certRequested = true
David Benjamin7a41d372016-07-09 11:21:54 -0700945 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
946 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
947 }
Adam Langley95c29f32014-06-20 12:00:00 -0700948
David Benjamin83c0bc92014-08-04 01:23:53 -0400949 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700950
David Benjamina6f82632016-07-01 18:44:02 -0400951 chainToSend, err = selectClientCertificate(c, certReq)
952 if err != nil {
953 return err
Adam Langley95c29f32014-06-20 12:00:00 -0700954 }
955
956 msg, err = c.readHandshake()
957 if err != nil {
958 return err
959 }
960 }
961
962 shd, ok := msg.(*serverHelloDoneMsg)
963 if !ok {
964 c.sendAlert(alertUnexpectedMessage)
965 return unexpectedMessageError(shd, msg)
966 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400967 hs.writeServerHash(shd.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700968
969 // If the server requested a certificate then we have to send a
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500970 // Certificate message in TLS, even if it's empty because we don't have
971 // a certificate to send. In SSL 3.0, skip the message and send a
972 // no_certificate warning alert.
Adam Langley95c29f32014-06-20 12:00:00 -0700973 if certRequested {
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500974 if c.vers == VersionSSL30 && chainToSend == nil {
975 c.sendAlert(alertNoCertficate)
976 } else if !c.config.Bugs.SkipClientCertificate {
977 certMsg := new(certificateMsg)
978 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -0400979 for _, certData := range chainToSend.Certificate {
980 certMsg.certificates = append(certMsg.certificates, certificateEntry{
981 data: certData,
982 })
983 }
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500984 }
985 hs.writeClientHash(certMsg.marshal())
986 c.writeRecord(recordTypeHandshake, certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700987 }
Adam Langley95c29f32014-06-20 12:00:00 -0700988 }
989
David Benjamin48cae082014-10-27 01:06:24 -0400990 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, leaf)
Adam Langley95c29f32014-06-20 12:00:00 -0700991 if err != nil {
992 c.sendAlert(alertInternalError)
993 return err
994 }
995 if ckx != nil {
David Benjaminf3ec83d2014-07-21 22:42:34 -0400996 if c.config.Bugs.EarlyChangeCipherSpec < 2 {
David Benjamin83c0bc92014-08-04 01:23:53 -0400997 hs.writeClientHash(ckx.marshal())
David Benjaminf3ec83d2014-07-21 22:42:34 -0400998 }
Adam Langley95c29f32014-06-20 12:00:00 -0700999 c.writeRecord(recordTypeHandshake, ckx.marshal())
1000 }
1001
Nick Harperb3d51be2016-07-01 11:43:18 -04001002 if hs.serverHello.extensions.extendedMasterSecret && c.vers >= VersionTLS10 {
Adam Langley75712922014-10-10 16:23:43 -07001003 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1004 c.extendedMasterSecret = true
1005 } else {
1006 if c.config.Bugs.RequireExtendedMasterSecret {
1007 return errors.New("tls: extended master secret required but not supported by peer")
1008 }
1009 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
1010 }
David Benjamine098ec22014-08-27 23:13:20 -04001011
Adam Langley95c29f32014-06-20 12:00:00 -07001012 if chainToSend != nil {
Adam Langley95c29f32014-06-20 12:00:00 -07001013 certVerify := &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001014 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001015 }
1016
David Benjamin72dc7832015-03-16 17:49:43 -04001017 // Determine the hash to sign.
Nick Harper60edffd2016-06-21 15:19:24 -07001018 privKey := c.config.Certificates[0].PrivateKey
David Benjamin72dc7832015-03-16 17:49:43 -04001019
Nick Harper60edffd2016-06-21 15:19:24 -07001020 if certVerify.hasSignatureAlgorithm {
David Benjamin0a8deb22016-07-09 21:02:01 -07001021 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
Nick Harper60edffd2016-06-21 15:19:24 -07001022 if err != nil {
1023 c.sendAlert(alertInternalError)
1024 return err
Adam Langley95c29f32014-06-20 12:00:00 -07001025 }
Nick Harper60edffd2016-06-21 15:19:24 -07001026 }
1027
1028 if c.vers > VersionSSL30 {
David Benjamin5208fd42016-07-13 21:43:25 -04001029 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, hs.finishedHash.buffer)
David Benjamina95e9f32016-07-08 16:28:04 -07001030 if err == nil && c.config.Bugs.SendSignatureAlgorithm != 0 {
1031 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
1032 }
Nick Harper60edffd2016-06-21 15:19:24 -07001033 } else {
1034 // SSL 3.0's client certificate construction is
1035 // incompatible with signatureAlgorithm.
1036 rsaKey, ok := privKey.(*rsa.PrivateKey)
1037 if !ok {
1038 err = errors.New("unsupported signature type for client certificate")
1039 } else {
1040 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
David Benjamin5208fd42016-07-13 21:43:25 -04001041 if c.config.Bugs.InvalidSignature {
Nick Harper60edffd2016-06-21 15:19:24 -07001042 digest[0] ^= 0x80
1043 }
1044 certVerify.signature, err = rsa.SignPKCS1v15(c.config.rand(), rsaKey, crypto.MD5SHA1, digest)
1045 }
Adam Langley95c29f32014-06-20 12:00:00 -07001046 }
1047 if err != nil {
1048 c.sendAlert(alertInternalError)
1049 return errors.New("tls: failed to sign handshake with client certificate: " + err.Error())
1050 }
Adam Langley95c29f32014-06-20 12:00:00 -07001051
David Benjamin83c0bc92014-08-04 01:23:53 -04001052 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001053 c.writeRecord(recordTypeHandshake, certVerify.marshal())
1054 }
David Benjamin82261be2016-07-07 14:32:50 -07001055 // flushHandshake will be called in sendFinished.
Adam Langley95c29f32014-06-20 12:00:00 -07001056
David Benjamine098ec22014-08-27 23:13:20 -04001057 hs.finishedHash.discardHandshakeBuffer()
1058
Adam Langley95c29f32014-06-20 12:00:00 -07001059 return nil
1060}
1061
David Benjamin75051442016-07-01 18:58:51 -04001062func (hs *clientHandshakeState) verifyCertificates(certMsg *certificateMsg) error {
1063 c := hs.c
1064
1065 if len(certMsg.certificates) == 0 {
1066 c.sendAlert(alertIllegalParameter)
1067 return errors.New("tls: no certificates sent")
1068 }
1069
1070 certs := make([]*x509.Certificate, len(certMsg.certificates))
Steven Valdeza833c352016-11-01 13:39:36 -04001071 for i, certEntry := range certMsg.certificates {
1072 cert, err := x509.ParseCertificate(certEntry.data)
David Benjamin75051442016-07-01 18:58:51 -04001073 if err != nil {
1074 c.sendAlert(alertBadCertificate)
1075 return errors.New("tls: failed to parse certificate from server: " + err.Error())
1076 }
1077 certs[i] = cert
1078 }
1079
1080 if !c.config.InsecureSkipVerify {
1081 opts := x509.VerifyOptions{
1082 Roots: c.config.RootCAs,
1083 CurrentTime: c.config.time(),
1084 DNSName: c.config.ServerName,
1085 Intermediates: x509.NewCertPool(),
1086 }
1087
1088 for i, cert := range certs {
1089 if i == 0 {
1090 continue
1091 }
1092 opts.Intermediates.AddCert(cert)
1093 }
1094 var err error
1095 c.verifiedChains, err = certs[0].Verify(opts)
1096 if err != nil {
1097 c.sendAlert(alertBadCertificate)
1098 return err
1099 }
1100 }
1101
1102 switch certs[0].PublicKey.(type) {
1103 case *rsa.PublicKey, *ecdsa.PublicKey:
1104 break
1105 default:
1106 c.sendAlert(alertUnsupportedCertificate)
1107 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
1108 }
1109
1110 c.peerCertificates = certs
1111 return nil
1112}
1113
Adam Langley95c29f32014-06-20 12:00:00 -07001114func (hs *clientHandshakeState) establishKeys() error {
1115 c := hs.c
1116
1117 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001118 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 -07001119 var clientCipher, serverCipher interface{}
1120 var clientHash, serverHash macFunction
1121 if hs.suite.cipher != nil {
1122 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
1123 clientHash = hs.suite.mac(c.vers, clientMAC)
1124 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
1125 serverHash = hs.suite.mac(c.vers, serverMAC)
1126 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001127 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1128 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001129 }
1130
1131 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
1132 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
1133 return nil
1134}
1135
David Benjamin75101402016-07-01 13:40:23 -04001136func (hs *clientHandshakeState) processServerExtensions(serverExtensions *serverExtensions) error {
1137 c := hs.c
1138
David Benjamin8d315d72016-07-18 01:03:18 +02001139 if c.vers < VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001140 if c.config.Bugs.RequireRenegotiationInfo && serverExtensions.secureRenegotiation == nil {
1141 return errors.New("tls: renegotiation extension missing")
1142 }
David Benjamin75101402016-07-01 13:40:23 -04001143
Nick Harperb41d2e42016-07-01 17:50:32 -04001144 if len(c.clientVerify) > 0 && !c.noRenegotiationInfo() {
1145 var expectedRenegInfo []byte
1146 expectedRenegInfo = append(expectedRenegInfo, c.clientVerify...)
1147 expectedRenegInfo = append(expectedRenegInfo, c.serverVerify...)
1148 if !bytes.Equal(serverExtensions.secureRenegotiation, expectedRenegInfo) {
1149 c.sendAlert(alertHandshakeFailure)
1150 return fmt.Errorf("tls: renegotiation mismatch")
1151 }
David Benjamin75101402016-07-01 13:40:23 -04001152 }
David Benjamincea0ab42016-07-14 12:33:14 -04001153 } else if serverExtensions.secureRenegotiation != nil {
1154 return errors.New("tls: renegotiation info sent in TLS 1.3")
David Benjamin75101402016-07-01 13:40:23 -04001155 }
1156
1157 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
1158 if serverExtensions.customExtension != *expected {
1159 return fmt.Errorf("tls: bad custom extension contents %q", serverExtensions.customExtension)
1160 }
1161 }
1162
1163 clientDidNPN := hs.hello.nextProtoNeg
1164 clientDidALPN := len(hs.hello.alpnProtocols) > 0
1165 serverHasNPN := serverExtensions.nextProtoNeg
1166 serverHasALPN := len(serverExtensions.alpnProtocol) > 0
1167
1168 if !clientDidNPN && serverHasNPN {
1169 c.sendAlert(alertHandshakeFailure)
1170 return errors.New("server advertised unrequested NPN extension")
1171 }
1172
1173 if !clientDidALPN && serverHasALPN {
1174 c.sendAlert(alertHandshakeFailure)
1175 return errors.New("server advertised unrequested ALPN extension")
1176 }
1177
1178 if serverHasNPN && serverHasALPN {
1179 c.sendAlert(alertHandshakeFailure)
1180 return errors.New("server advertised both NPN and ALPN extensions")
1181 }
1182
1183 if serverHasALPN {
1184 c.clientProtocol = serverExtensions.alpnProtocol
1185 c.clientProtocolFallback = false
1186 c.usedALPN = true
1187 }
1188
David Benjamin8d315d72016-07-18 01:03:18 +02001189 if serverHasNPN && c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001190 c.sendAlert(alertHandshakeFailure)
1191 return errors.New("server advertised NPN over TLS 1.3")
1192 }
1193
David Benjamin75101402016-07-01 13:40:23 -04001194 if !hs.hello.channelIDSupported && serverExtensions.channelIDRequested {
1195 c.sendAlert(alertHandshakeFailure)
1196 return errors.New("server advertised unrequested Channel ID extension")
1197 }
1198
David Benjamin8d315d72016-07-18 01:03:18 +02001199 if serverExtensions.extendedMasterSecret && c.vers >= VersionTLS13 {
David Benjamine9077652016-07-13 21:02:08 -04001200 return errors.New("tls: server advertised extended master secret over TLS 1.3")
1201 }
1202
David Benjamin8d315d72016-07-18 01:03:18 +02001203 if serverExtensions.ticketSupported && c.vers >= VersionTLS13 {
Steven Valdez143e8b32016-07-11 13:19:03 -04001204 return errors.New("tls: server advertised ticket extension over TLS 1.3")
1205 }
1206
Steven Valdeza833c352016-11-01 13:39:36 -04001207 if serverExtensions.ocspStapling && c.vers >= VersionTLS13 {
1208 return errors.New("tls: server advertised OCSP in ServerHello over TLS 1.3")
1209 }
1210
1211 if len(serverExtensions.sctList) > 0 && c.vers >= VersionTLS13 {
1212 return errors.New("tls: server advertised SCTs in ServerHello over TLS 1.3")
1213 }
1214
David Benjamin75101402016-07-01 13:40:23 -04001215 if serverExtensions.srtpProtectionProfile != 0 {
1216 if serverExtensions.srtpMasterKeyIdentifier != "" {
1217 return errors.New("tls: server selected SRTP MKI value")
1218 }
1219
1220 found := false
1221 for _, p := range c.config.SRTPProtectionProfiles {
1222 if p == serverExtensions.srtpProtectionProfile {
1223 found = true
1224 break
1225 }
1226 }
1227 if !found {
1228 return errors.New("tls: server advertised unsupported SRTP profile")
1229 }
1230
1231 c.srtpProtectionProfile = serverExtensions.srtpProtectionProfile
1232 }
1233
1234 return nil
1235}
1236
Adam Langley95c29f32014-06-20 12:00:00 -07001237func (hs *clientHandshakeState) serverResumedSession() bool {
1238 // If the server responded with the same sessionId then it means the
1239 // sessionTicket is being used to resume a TLS session.
1240 return hs.session != nil && hs.hello.sessionId != nil &&
1241 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
1242}
1243
1244func (hs *clientHandshakeState) processServerHello() (bool, error) {
1245 c := hs.c
1246
Adam Langley95c29f32014-06-20 12:00:00 -07001247 if hs.serverResumedSession() {
David Benjamin4b27d9f2015-05-12 22:42:52 -04001248 // For test purposes, assert that the server never accepts the
1249 // resumption offer on renegotiation.
1250 if c.cipherSuite != nil && c.config.Bugs.FailIfResumeOnRenego {
1251 return false, errors.New("tls: server resumed session on renegotiation")
1252 }
1253
Nick Harperb3d51be2016-07-01 11:43:18 -04001254 if hs.serverHello.extensions.sctList != nil {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001255 return false, errors.New("tls: server sent SCT extension on session resumption")
1256 }
1257
Nick Harperb3d51be2016-07-01 11:43:18 -04001258 if hs.serverHello.extensions.ocspStapling {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001259 return false, errors.New("tls: server sent OCSP extension on session resumption")
1260 }
1261
Adam Langley95c29f32014-06-20 12:00:00 -07001262 // Restore masterSecret and peerCerts from previous state
1263 hs.masterSecret = hs.session.masterSecret
1264 c.peerCertificates = hs.session.serverCertificates
Adam Langley75712922014-10-10 16:23:43 -07001265 c.extendedMasterSecret = hs.session.extendedMasterSecret
Paul Lietar62be8ac2015-09-16 10:03:30 +01001266 c.sctList = hs.session.sctList
1267 c.ocspResponse = hs.session.ocspResponse
David Benjamine098ec22014-08-27 23:13:20 -04001268 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001269 return true, nil
1270 }
Paul Lietar62be8ac2015-09-16 10:03:30 +01001271
Nick Harperb3d51be2016-07-01 11:43:18 -04001272 if hs.serverHello.extensions.sctList != nil {
1273 c.sctList = hs.serverHello.extensions.sctList
Paul Lietar62be8ac2015-09-16 10:03:30 +01001274 }
1275
Adam Langley95c29f32014-06-20 12:00:00 -07001276 return false, nil
1277}
1278
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001279func (hs *clientHandshakeState) readFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001280 c := hs.c
1281
1282 c.readRecord(recordTypeChangeCipherSpec)
1283 if err := c.in.error(); err != nil {
1284 return err
1285 }
1286
1287 msg, err := c.readHandshake()
1288 if err != nil {
1289 return err
1290 }
1291 serverFinished, ok := msg.(*finishedMsg)
1292 if !ok {
1293 c.sendAlert(alertUnexpectedMessage)
1294 return unexpectedMessageError(serverFinished, msg)
1295 }
1296
David Benjaminf3ec83d2014-07-21 22:42:34 -04001297 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
1298 verify := hs.finishedHash.serverSum(hs.masterSecret)
1299 if len(verify) != len(serverFinished.verifyData) ||
1300 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
1301 c.sendAlert(alertHandshakeFailure)
1302 return errors.New("tls: server's Finished message was incorrect")
1303 }
Adam Langley95c29f32014-06-20 12:00:00 -07001304 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001305 c.serverVerify = append(c.serverVerify[:0], serverFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001306 copy(out, serverFinished.verifyData)
David Benjamin83c0bc92014-08-04 01:23:53 -04001307 hs.writeServerHash(serverFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001308 return nil
1309}
1310
1311func (hs *clientHandshakeState) readSessionTicket() error {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001312 c := hs.c
1313
1314 // Create a session with no server identifier. Either a
1315 // session ID or session ticket will be attached.
1316 session := &ClientSessionState{
1317 vers: c.vers,
1318 cipherSuite: hs.suite.id,
1319 masterSecret: hs.masterSecret,
Nick Harperc9846112016-10-17 15:05:35 -07001320 handshakeHash: hs.finishedHash.Sum(),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001321 serverCertificates: c.peerCertificates,
Paul Lietar62be8ac2015-09-16 10:03:30 +01001322 sctList: c.sctList,
1323 ocspResponse: c.ocspResponse,
Nick Harper0b3625b2016-07-25 16:16:28 -07001324 ticketExpiration: c.config.time().Add(time.Duration(7 * 24 * time.Hour)),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001325 }
1326
Nick Harperb3d51be2016-07-01 11:43:18 -04001327 if !hs.serverHello.extensions.ticketSupported {
David Benjamind98452d2015-06-16 14:16:23 -04001328 if c.config.Bugs.ExpectNewTicket {
1329 return errors.New("tls: expected new ticket")
1330 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001331 if hs.session == nil && len(hs.serverHello.sessionId) > 0 {
1332 session.sessionId = hs.serverHello.sessionId
1333 hs.session = session
1334 }
Adam Langley95c29f32014-06-20 12:00:00 -07001335 return nil
1336 }
1337
David Benjaminc7ce9772015-10-09 19:32:41 -04001338 if c.vers == VersionSSL30 {
1339 return errors.New("tls: negotiated session tickets in SSL 3.0")
1340 }
1341
Adam Langley95c29f32014-06-20 12:00:00 -07001342 msg, err := c.readHandshake()
1343 if err != nil {
1344 return err
1345 }
1346 sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
1347 if !ok {
1348 c.sendAlert(alertUnexpectedMessage)
1349 return unexpectedMessageError(sessionTicketMsg, msg)
1350 }
Adam Langley95c29f32014-06-20 12:00:00 -07001351
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001352 session.sessionTicket = sessionTicketMsg.ticket
1353 hs.session = session
Adam Langley95c29f32014-06-20 12:00:00 -07001354
David Benjamind30a9902014-08-24 01:44:23 -04001355 hs.writeServerHash(sessionTicketMsg.marshal())
1356
Adam Langley95c29f32014-06-20 12:00:00 -07001357 return nil
1358}
1359
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001360func (hs *clientHandshakeState) sendFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001361 c := hs.c
1362
David Benjamin0b8d5da2016-07-15 00:39:56 -04001363 var postCCSMsgs [][]byte
David Benjamin83c0bc92014-08-04 01:23:53 -04001364 seqno := hs.c.sendHandshakeSeq
Nick Harperb3d51be2016-07-01 11:43:18 -04001365 if hs.serverHello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001366 nextProto := new(nextProtoMsg)
Nick Harperb3d51be2016-07-01 11:43:18 -04001367 proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.extensions.nextProtos)
Adam Langley95c29f32014-06-20 12:00:00 -07001368 nextProto.proto = proto
1369 c.clientProtocol = proto
1370 c.clientProtocolFallback = fallback
1371
David Benjamin86271ee2014-07-21 16:14:03 -04001372 nextProtoBytes := nextProto.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -04001373 hs.writeHash(nextProtoBytes, seqno)
1374 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001375 postCCSMsgs = append(postCCSMsgs, nextProtoBytes)
Adam Langley95c29f32014-06-20 12:00:00 -07001376 }
1377
Nick Harperb3d51be2016-07-01 11:43:18 -04001378 if hs.serverHello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001379 var resumeHash []byte
1380 if isResume {
1381 resumeHash = hs.session.handshakeHash
1382 }
Nick Harper60a85cb2016-09-23 16:25:11 -07001383 channelIDMsgBytes, err := hs.writeChannelIDMessage(hs.finishedHash.hashForChannelID(resumeHash))
David Benjamind30a9902014-08-24 01:44:23 -04001384 if err != nil {
1385 return err
1386 }
David Benjamin24599a82016-06-30 18:56:53 -04001387 hs.writeHash(channelIDMsgBytes, seqno)
David Benjamind30a9902014-08-24 01:44:23 -04001388 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001389 postCCSMsgs = append(postCCSMsgs, channelIDMsgBytes)
David Benjamind30a9902014-08-24 01:44:23 -04001390 }
1391
Adam Langley95c29f32014-06-20 12:00:00 -07001392 finished := new(finishedMsg)
David Benjaminf3ec83d2014-07-21 22:42:34 -04001393 if c.config.Bugs.EarlyChangeCipherSpec == 2 {
1394 finished.verifyData = hs.finishedHash.clientSum(nil)
1395 } else {
1396 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
1397 }
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001398 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001399 if c.config.Bugs.BadFinished {
1400 finished.verifyData[0]++
1401 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001402 c.clientVerify = append(c.clientVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001403 hs.finishedBytes = finished.marshal()
1404 hs.writeHash(hs.finishedBytes, seqno)
David Benjamin0b8d5da2016-07-15 00:39:56 -04001405 postCCSMsgs = append(postCCSMsgs, hs.finishedBytes)
David Benjamin86271ee2014-07-21 16:14:03 -04001406
1407 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001408 c.writeRecord(recordTypeHandshake, postCCSMsgs[0][:5])
1409 postCCSMsgs[0] = postCCSMsgs[0][5:]
David Benjamin61672812016-07-14 23:10:43 -04001410 } else if c.config.Bugs.SendUnencryptedFinished {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001411 c.writeRecord(recordTypeHandshake, postCCSMsgs[0])
1412 postCCSMsgs = postCCSMsgs[1:]
David Benjamin86271ee2014-07-21 16:14:03 -04001413 }
David Benjamin582ba042016-07-07 12:33:25 -07001414 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001415
1416 if !c.config.Bugs.SkipChangeCipherSpec &&
1417 c.config.Bugs.EarlyChangeCipherSpec == 0 {
David Benjamin8411b242015-11-26 12:07:28 -05001418 ccs := []byte{1}
1419 if c.config.Bugs.BadChangeCipherSpec != nil {
1420 ccs = c.config.Bugs.BadChangeCipherSpec
1421 }
1422 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamin86271ee2014-07-21 16:14:03 -04001423 }
1424
David Benjamin4189bd92015-01-25 23:52:39 -05001425 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1426 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1427 }
David Benjamindc3da932015-03-12 15:09:02 -04001428 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1429 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1430 return errors.New("tls: simulating post-CCS alert")
1431 }
David Benjamin4189bd92015-01-25 23:52:39 -05001432
David Benjamin0b8d5da2016-07-15 00:39:56 -04001433 if !c.config.Bugs.SkipFinished {
1434 for _, msg := range postCCSMsgs {
1435 c.writeRecord(recordTypeHandshake, msg)
1436 }
David Benjamin02edcd02016-07-27 17:40:37 -04001437
1438 if c.config.Bugs.SendExtraFinished {
1439 c.writeRecord(recordTypeHandshake, finished.marshal())
1440 }
1441
David Benjamin582ba042016-07-07 12:33:25 -07001442 c.flushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -05001443 }
Adam Langley95c29f32014-06-20 12:00:00 -07001444 return nil
1445}
1446
Nick Harper60a85cb2016-09-23 16:25:11 -07001447func (hs *clientHandshakeState) writeChannelIDMessage(channelIDHash []byte) ([]byte, error) {
1448 c := hs.c
1449 channelIDMsg := new(channelIDMsg)
1450 if c.config.ChannelID.Curve != elliptic.P256() {
1451 return nil, fmt.Errorf("tls: Channel ID is not on P-256.")
1452 }
1453 r, s, err := ecdsa.Sign(c.config.rand(), c.config.ChannelID, channelIDHash)
1454 if err != nil {
1455 return nil, err
1456 }
1457 channelID := make([]byte, 128)
1458 writeIntPadded(channelID[0:32], c.config.ChannelID.X)
1459 writeIntPadded(channelID[32:64], c.config.ChannelID.Y)
1460 writeIntPadded(channelID[64:96], r)
1461 writeIntPadded(channelID[96:128], s)
1462 if c.config.Bugs.InvalidChannelIDSignature {
1463 channelID[64] ^= 1
1464 }
1465 channelIDMsg.channelID = channelID
1466
1467 c.channelID = &c.config.ChannelID.PublicKey
1468
1469 return channelIDMsg.marshal(), nil
1470}
1471
David Benjamin83c0bc92014-08-04 01:23:53 -04001472func (hs *clientHandshakeState) writeClientHash(msg []byte) {
1473 // writeClientHash is called before writeRecord.
1474 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1475}
1476
1477func (hs *clientHandshakeState) writeServerHash(msg []byte) {
1478 // writeServerHash is called after readHandshake.
1479 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1480}
1481
1482func (hs *clientHandshakeState) writeHash(msg []byte, seqno uint16) {
1483 if hs.c.isDTLS {
1484 // This is somewhat hacky. DTLS hashes a slightly different format.
1485 // First, the TLS header.
1486 hs.finishedHash.Write(msg[:4])
1487 // Then the sequence number and reassembled fragment offset (always 0).
1488 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1489 // Then the reassembled fragment (always equal to the message length).
1490 hs.finishedHash.Write(msg[1:4])
1491 // And then the message body.
1492 hs.finishedHash.Write(msg[4:])
1493 } else {
1494 hs.finishedHash.Write(msg)
1495 }
1496}
1497
David Benjamina6f82632016-07-01 18:44:02 -04001498// selectClientCertificate selects a certificate for use with the given
1499// certificate, or none if none match. It may return a particular certificate or
1500// nil on success, or an error on internal error.
1501func selectClientCertificate(c *Conn, certReq *certificateRequestMsg) (*Certificate, error) {
1502 // RFC 4346 on the certificateAuthorities field:
1503 // A list of the distinguished names of acceptable certificate
1504 // authorities. These distinguished names may specify a desired
1505 // distinguished name for a root CA or for a subordinate CA; thus, this
1506 // message can be used to describe both known roots and a desired
1507 // authorization space. If the certificate_authorities list is empty
1508 // then the client MAY send any certificate of the appropriate
1509 // ClientCertificateType, unless there is some external arrangement to
1510 // the contrary.
1511
1512 var rsaAvail, ecdsaAvail bool
Nick Harperb41d2e42016-07-01 17:50:32 -04001513 if !certReq.hasRequestContext {
1514 for _, certType := range certReq.certificateTypes {
1515 switch certType {
1516 case CertTypeRSASign:
1517 rsaAvail = true
1518 case CertTypeECDSASign:
1519 ecdsaAvail = true
1520 }
David Benjamina6f82632016-07-01 18:44:02 -04001521 }
1522 }
1523
1524 // We need to search our list of client certs for one
1525 // where SignatureAlgorithm is RSA and the Issuer is in
1526 // certReq.certificateAuthorities
1527findCert:
1528 for i, chain := range c.config.Certificates {
Nick Harperb41d2e42016-07-01 17:50:32 -04001529 if !certReq.hasRequestContext && !rsaAvail && !ecdsaAvail {
David Benjamina6f82632016-07-01 18:44:02 -04001530 continue
1531 }
1532
1533 // Ensure the private key supports one of the advertised
1534 // signature algorithms.
1535 if certReq.hasSignatureAlgorithm {
David Benjamin0a8deb22016-07-09 21:02:01 -07001536 if _, err := selectSignatureAlgorithm(c.vers, chain.PrivateKey, c.config, certReq.signatureAlgorithms); err != nil {
David Benjamina6f82632016-07-01 18:44:02 -04001537 continue
1538 }
1539 }
1540
1541 for j, cert := range chain.Certificate {
1542 x509Cert := chain.Leaf
1543 // parse the certificate if this isn't the leaf
1544 // node, or if chain.Leaf was nil
1545 if j != 0 || x509Cert == nil {
1546 var err error
1547 if x509Cert, err = x509.ParseCertificate(cert); err != nil {
1548 c.sendAlert(alertInternalError)
1549 return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
1550 }
1551 }
1552
Nick Harperb41d2e42016-07-01 17:50:32 -04001553 if !certReq.hasRequestContext {
1554 switch {
1555 case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
1556 case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
1557 default:
1558 continue findCert
1559 }
David Benjamina6f82632016-07-01 18:44:02 -04001560 }
1561
1562 if len(certReq.certificateAuthorities) == 0 {
1563 // They gave us an empty list, so just take the
1564 // first certificate of valid type from
1565 // c.config.Certificates.
1566 return &chain, nil
1567 }
1568
1569 for _, ca := range certReq.certificateAuthorities {
1570 if bytes.Equal(x509Cert.RawIssuer, ca) {
1571 return &chain, nil
1572 }
1573 }
1574 }
1575 }
1576
1577 return nil, nil
1578}
1579
Adam Langley95c29f32014-06-20 12:00:00 -07001580// clientSessionCacheKey returns a key used to cache sessionTickets that could
1581// be used to resume previously negotiated TLS sessions with a server.
1582func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
1583 if len(config.ServerName) > 0 {
1584 return config.ServerName
1585 }
1586 return serverAddr.String()
1587}
1588
David Benjaminfa055a22014-09-15 16:51:51 -04001589// mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
1590// given list of possible protocols and a list of the preference order. The
1591// first list must not be empty. It returns the resulting protocol and flag
Adam Langley95c29f32014-06-20 12:00:00 -07001592// indicating if the fallback case was reached.
David Benjaminfa055a22014-09-15 16:51:51 -04001593func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
1594 for _, s := range preferenceProtos {
1595 for _, c := range protos {
Adam Langley95c29f32014-06-20 12:00:00 -07001596 if s == c {
1597 return s, false
1598 }
1599 }
1600 }
1601
David Benjaminfa055a22014-09-15 16:51:51 -04001602 return protos[0], true
Adam Langley95c29f32014-06-20 12:00:00 -07001603}
David Benjamind30a9902014-08-24 01:44:23 -04001604
1605// writeIntPadded writes x into b, padded up with leading zeros as
1606// needed.
1607func writeIntPadded(b []byte, x *big.Int) {
1608 for i := range b {
1609 b[i] = 0
1610 }
1611 xb := x.Bytes()
1612 copy(b[len(b)-len(xb):], xb)
1613}
Steven Valdeza833c352016-11-01 13:39:36 -04001614
1615func generatePSKBinders(hello *clientHelloMsg, pskCipherSuite *cipherSuite, psk, transcript []byte, config *Config) {
1616 if config.Bugs.SendNoPSKBinder {
1617 return
1618 }
1619
1620 binderLen := pskCipherSuite.hash().Size()
1621 if config.Bugs.SendShortPSKBinder {
1622 binderLen--
1623 }
1624
1625 // Fill hello.pskBinders with appropriate length arrays of zeros so the
1626 // length prefixes are correct when computing the binder over the truncated
1627 // ClientHello message.
1628 hello.pskBinders = make([][]byte, len(hello.pskIdentities))
1629 for i := range hello.pskIdentities {
1630 hello.pskBinders[i] = make([]byte, binderLen)
1631 }
1632
1633 helloBytes := hello.marshal()
1634 binderSize := len(hello.pskBinders)*(binderLen+1) + 2
1635 truncatedHello := helloBytes[:len(helloBytes)-binderSize]
1636 binder := computePSKBinder(psk, resumptionPSKBinderLabel, pskCipherSuite, transcript, truncatedHello)
1637 if config.Bugs.SendShortPSKBinder {
1638 binder = binder[:binderLen]
1639 }
1640 if config.Bugs.SendInvalidPSKBinder {
1641 binder[0] ^= 1
1642 }
1643
1644 for i := range hello.pskBinders {
1645 hello.pskBinders[i] = binder
1646 }
1647
1648 hello.raw = nil
1649}