blob: 02daa7814e83257aa1cf3684097b129be33c7284 [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,
David Benjamin6f600d62016-12-21 16:06:54 -050084 shortHeaderSupported: c.config.Bugs.EnableShortHeader,
Adam Langley95c29f32014-06-20 12:00:00 -070085 }
86
David Benjamin163c9562016-08-29 23:14:17 -040087 disableEMS := c.config.Bugs.NoExtendedMasterSecret
88 if c.cipherSuite != nil {
89 disableEMS = c.config.Bugs.NoExtendedMasterSecretOnRenegotiation
90 }
91
92 if disableEMS {
Adam Langley75712922014-10-10 16:23:43 -070093 hello.extendedMasterSecret = false
94 }
95
David Benjamin55a43642015-04-20 14:45:55 -040096 if c.config.Bugs.NoSupportedCurves {
97 hello.supportedCurves = nil
98 }
99
Steven Valdeza833c352016-11-01 13:39:36 -0400100 if len(c.config.Bugs.SendPSKKeyExchangeModes) != 0 {
101 hello.pskKEModes = c.config.Bugs.SendPSKKeyExchangeModes
102 }
103
David Benjaminc241d792016-09-09 10:34:20 -0400104 if c.config.Bugs.SendCompressionMethods != nil {
105 hello.compressionMethods = c.config.Bugs.SendCompressionMethods
106 }
107
David Benjamina81967b2016-12-22 09:16:57 -0500108 if c.config.Bugs.SendSupportedPointFormats != nil {
109 hello.supportedPoints = c.config.Bugs.SendSupportedPointFormats
110 }
111
Adam Langley2ae77d22014-10-28 17:29:33 -0700112 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
113 if c.config.Bugs.BadRenegotiationInfo {
114 hello.secureRenegotiation = append(hello.secureRenegotiation, c.clientVerify...)
115 hello.secureRenegotiation[0] ^= 0x80
116 } else {
117 hello.secureRenegotiation = c.clientVerify
118 }
119 }
120
David Benjamin3e052de2015-11-25 20:10:31 -0500121 if c.noRenegotiationInfo() {
David Benjaminca6554b2014-11-08 12:31:52 -0500122 hello.secureRenegotiation = nil
123 }
124
Nick Harperb41d2e42016-07-01 17:50:32 -0400125 var keyShares map[CurveID]ecdhCurve
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400126 if maxVersion >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -0400127 keyShares = make(map[CurveID]ecdhCurve)
Nick Harperdcfbc672016-07-16 17:47:31 +0200128 hello.hasKeyShares = true
David Benjamin7e1f9842016-09-20 19:24:40 -0400129 hello.trailingKeyShareData = c.config.Bugs.TrailingKeyShareData
Nick Harperdcfbc672016-07-16 17:47:31 +0200130 curvesToSend := c.config.defaultCurves()
Nick Harperb41d2e42016-07-01 17:50:32 -0400131 for _, curveID := range hello.supportedCurves {
Nick Harperdcfbc672016-07-16 17:47:31 +0200132 if !curvesToSend[curveID] {
133 continue
134 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400135 curve, ok := curveForCurveID(curveID)
136 if !ok {
137 continue
138 }
139 publicKey, err := curve.offer(c.config.rand())
140 if err != nil {
141 return err
142 }
Steven Valdez0ee2e112016-07-15 06:51:15 -0400143
144 if c.config.Bugs.SendCurve != 0 {
145 curveID = c.config.Bugs.SendCurve
146 }
147 if c.config.Bugs.InvalidECDHPoint {
148 publicKey[0] ^= 0xff
149 }
150
Nick Harperb41d2e42016-07-01 17:50:32 -0400151 hello.keyShares = append(hello.keyShares, keyShareEntry{
152 group: curveID,
153 keyExchange: publicKey,
154 })
155 keyShares[curveID] = curve
Steven Valdez143e8b32016-07-11 13:19:03 -0400156
157 if c.config.Bugs.DuplicateKeyShares {
158 hello.keyShares = append(hello.keyShares, hello.keyShares[len(hello.keyShares)-1])
159 }
160 }
161
162 if c.config.Bugs.MissingKeyShare {
Steven Valdez5440fe02016-07-18 12:40:30 -0400163 hello.hasKeyShares = false
Nick Harperb41d2e42016-07-01 17:50:32 -0400164 }
165 }
166
Adam Langley95c29f32014-06-20 12:00:00 -0700167 possibleCipherSuites := c.config.cipherSuites()
168 hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
169
170NextCipherSuite:
171 for _, suiteId := range possibleCipherSuites {
172 for _, suite := range cipherSuites {
173 if suite.id != suiteId {
174 continue
175 }
David Benjamin5ecb88b2016-10-04 17:51:35 -0400176 // Don't advertise TLS 1.2-only cipher suites unless
177 // we're attempting TLS 1.2.
178 if maxVersion < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
179 continue
180 }
181 // Don't advertise non-DTLS cipher suites in DTLS.
182 if c.isDTLS && suite.flags&suiteNoDTLS != 0 {
183 continue
David Benjamin83c0bc92014-08-04 01:23:53 -0400184 }
Adam Langley95c29f32014-06-20 12:00:00 -0700185 hello.cipherSuites = append(hello.cipherSuites, suiteId)
186 continue NextCipherSuite
187 }
188 }
189
David Benjamin5ecb88b2016-10-04 17:51:35 -0400190 if c.config.Bugs.AdvertiseAllConfiguredCiphers {
191 hello.cipherSuites = possibleCipherSuites
192 }
193
Adam Langley5021b222015-06-12 18:27:58 -0700194 if c.config.Bugs.SendRenegotiationSCSV {
195 hello.cipherSuites = append(hello.cipherSuites, renegotiationSCSV)
196 }
197
David Benjaminbef270a2014-08-02 04:22:02 -0400198 if c.config.Bugs.SendFallbackSCSV {
199 hello.cipherSuites = append(hello.cipherSuites, fallbackSCSV)
200 }
201
Adam Langley95c29f32014-06-20 12:00:00 -0700202 _, err := io.ReadFull(c.config.rand(), hello.random)
203 if err != nil {
204 c.sendAlert(alertInternalError)
205 return errors.New("tls: short read from Rand: " + err.Error())
206 }
207
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400208 if maxVersion >= VersionTLS12 && !c.config.Bugs.NoSignatureAlgorithms {
David Benjamin7a41d372016-07-09 11:21:54 -0700209 hello.signatureAlgorithms = c.config.verifySignatureAlgorithms()
Adam Langley95c29f32014-06-20 12:00:00 -0700210 }
211
212 var session *ClientSessionState
213 var cacheKey string
214 sessionCache := c.config.ClientSessionCache
Adam Langley95c29f32014-06-20 12:00:00 -0700215
216 if sessionCache != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500217 hello.ticketSupported = !c.config.SessionTicketsDisabled
Adam Langley95c29f32014-06-20 12:00:00 -0700218
219 // Try to resume a previously negotiated TLS session, if
220 // available.
221 cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
Nick Harper0b3625b2016-07-25 16:16:28 -0700222 // TODO(nharper): Support storing more than one session
223 // ticket for TLS 1.3.
Adam Langley95c29f32014-06-20 12:00:00 -0700224 candidateSession, ok := sessionCache.Get(cacheKey)
225 if ok {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500226 ticketOk := !c.config.SessionTicketsDisabled || candidateSession.sessionTicket == nil
227
Adam Langley95c29f32014-06-20 12:00:00 -0700228 // Check that the ciphersuite/version used for the
229 // previous session are still valid.
230 cipherSuiteOk := false
David Benjamin2b02f4b2016-11-16 16:11:47 +0900231 if candidateSession.vers <= VersionTLS12 {
232 for _, id := range hello.cipherSuites {
233 if id == candidateSession.cipherSuite {
234 cipherSuiteOk = true
235 break
236 }
Adam Langley95c29f32014-06-20 12:00:00 -0700237 }
David Benjamin2b02f4b2016-11-16 16:11:47 +0900238 } else {
239 // TLS 1.3 allows the cipher to change on
240 // resumption.
241 cipherSuiteOk = true
Adam Langley95c29f32014-06-20 12:00:00 -0700242 }
243
Steven Valdezfdd10992016-09-15 16:27:05 -0400244 versOk := candidateSession.vers >= minVersion &&
245 candidateSession.vers <= maxVersion
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500246 if ticketOk && versOk && cipherSuiteOk {
Adam Langley95c29f32014-06-20 12:00:00 -0700247 session = candidateSession
248 }
249 }
250 }
251
Steven Valdeza833c352016-11-01 13:39:36 -0400252 var pskCipherSuite *cipherSuite
Nick Harper0b3625b2016-07-25 16:16:28 -0700253 if session != nil && c.config.time().Before(session.ticketExpiration) {
David Benjamind5a4ecb2016-07-18 01:17:13 +0200254 ticket := session.sessionTicket
David Benjamin4199b0d2016-11-01 13:58:25 -0400255 if c.config.Bugs.FilterTicket != nil && len(ticket) > 0 {
256 // Copy the ticket so FilterTicket may act in-place.
David Benjamind5a4ecb2016-07-18 01:17:13 +0200257 ticket = make([]byte, len(session.sessionTicket))
258 copy(ticket, session.sessionTicket)
David Benjamin4199b0d2016-11-01 13:58:25 -0400259
260 ticket, err = c.config.Bugs.FilterTicket(ticket)
261 if err != nil {
262 return err
Adam Langley38311732014-10-16 19:04:35 -0700263 }
David Benjamind5a4ecb2016-07-18 01:17:13 +0200264 }
265
David Benjamin405da482016-08-08 17:25:07 -0400266 if session.vers >= VersionTLS13 || c.config.Bugs.SendBothTickets {
Steven Valdeza833c352016-11-01 13:39:36 -0400267 pskCipherSuite = cipherSuiteFromID(session.cipherSuite)
268 if pskCipherSuite == nil {
269 return errors.New("tls: client session cache has invalid cipher suite")
270 }
Nick Harper0b3625b2016-07-25 16:16:28 -0700271 // TODO(nharper): Support sending more
272 // than one PSK identity.
Steven Valdeza833c352016-11-01 13:39:36 -0400273 ticketAge := uint32(c.config.time().Sub(session.ticketCreationTime) / time.Millisecond)
Steven Valdez5b986082016-09-01 12:29:49 -0400274 psk := pskIdentity{
Steven Valdeza833c352016-11-01 13:39:36 -0400275 ticket: ticket,
276 obfuscatedTicketAge: session.ticketAgeAdd + ticketAge,
Nick Harper0b3625b2016-07-25 16:16:28 -0700277 }
Steven Valdez5b986082016-09-01 12:29:49 -0400278 hello.pskIdentities = []pskIdentity{psk}
Steven Valdezaf3b8a92016-11-01 12:49:22 -0400279
280 if c.config.Bugs.ExtraPSKIdentity {
281 hello.pskIdentities = append(hello.pskIdentities, psk)
282 }
David Benjamin405da482016-08-08 17:25:07 -0400283 }
284
285 if session.vers < VersionTLS13 || c.config.Bugs.SendBothTickets {
286 if ticket != nil {
287 hello.sessionTicket = ticket
288 // A random session ID is used to detect when the
289 // server accepted the ticket and is resuming a session
290 // (see RFC 5077).
291 sessionIdLen := 16
292 if c.config.Bugs.OversizedSessionId {
293 sessionIdLen = 33
294 }
295 hello.sessionId = make([]byte, sessionIdLen)
296 if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
297 c.sendAlert(alertInternalError)
298 return errors.New("tls: short read from Rand: " + err.Error())
299 }
300 } else {
301 hello.sessionId = session.sessionId
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500302 }
Adam Langley95c29f32014-06-20 12:00:00 -0700303 }
304 }
305
Steven Valdezfdd10992016-09-15 16:27:05 -0400306 if maxVersion == VersionTLS13 && !c.config.Bugs.OmitSupportedVersions {
307 if hello.vers >= VersionTLS13 {
308 hello.vers = VersionTLS12
309 }
310 for version := maxVersion; version >= minVersion; version-- {
311 hello.supportedVersions = append(hello.supportedVersions, versionToWire(version, c.isDTLS))
312 }
313 }
314
315 if len(c.config.Bugs.SendSupportedVersions) > 0 {
316 hello.supportedVersions = c.config.Bugs.SendSupportedVersions
317 }
318
David Benjamineed24012016-08-13 19:26:00 -0400319 if c.config.Bugs.SendClientVersion != 0 {
320 hello.vers = c.config.Bugs.SendClientVersion
321 }
322
David Benjamin75f99142016-11-12 12:36:06 +0900323 if c.config.Bugs.SendCipherSuites != nil {
324 hello.cipherSuites = c.config.Bugs.SendCipherSuites
325 }
326
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500327 if c.config.Bugs.SendEarlyDataLength > 0 && !c.config.Bugs.OmitEarlyDataExtension {
328 hello.hasEarlyData = true
329 }
330
David Benjamind86c7672014-08-02 04:07:12 -0400331 var helloBytes []byte
332 if c.config.Bugs.SendV2ClientHello {
David Benjamin94d701b2014-11-30 13:54:41 -0500333 // Test that the peer left-pads random.
334 hello.random[0] = 0
David Benjamind86c7672014-08-02 04:07:12 -0400335 v2Hello := &v2ClientHelloMsg{
336 vers: hello.vers,
337 cipherSuites: hello.cipherSuites,
338 // No session resumption for V2ClientHello.
339 sessionId: nil,
David Benjamin94d701b2014-11-30 13:54:41 -0500340 challenge: hello.random[1:],
David Benjamind86c7672014-08-02 04:07:12 -0400341 }
342 helloBytes = v2Hello.marshal()
343 c.writeV2Record(helloBytes)
344 } else {
Steven Valdeza833c352016-11-01 13:39:36 -0400345 if len(hello.pskIdentities) > 0 {
346 generatePSKBinders(hello, pskCipherSuite, session.masterSecret, []byte{}, c.config)
347 }
David Benjamind86c7672014-08-02 04:07:12 -0400348 helloBytes = hello.marshal()
Steven Valdeza833c352016-11-01 13:39:36 -0400349
David Benjamin7964b182016-07-14 23:36:30 -0400350 if c.config.Bugs.PartialClientFinishedWithClientHello {
351 // Include one byte of Finished. We can compute it
352 // without completing the handshake. This assumes we
353 // negotiate TLS 1.3 with no HelloRetryRequest or
354 // CertificateRequest.
355 toWrite := make([]byte, 0, len(helloBytes)+1)
356 toWrite = append(toWrite, helloBytes...)
357 toWrite = append(toWrite, typeFinished)
358 c.writeRecord(recordTypeHandshake, toWrite)
359 } else {
360 c.writeRecord(recordTypeHandshake, helloBytes)
361 }
David Benjamind86c7672014-08-02 04:07:12 -0400362 }
David Benjamin582ba042016-07-07 12:33:25 -0700363 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700364
David Benjamin83f90402015-01-27 01:09:43 -0500365 if err := c.simulatePacketLoss(nil); err != nil {
366 return err
367 }
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500368 if c.config.Bugs.SendEarlyAlert {
369 c.sendAlert(alertHandshakeFailure)
370 }
371 if c.config.Bugs.SendEarlyDataLength > 0 {
372 c.sendFakeEarlyData(c.config.Bugs.SendEarlyDataLength)
373 }
Adam Langley95c29f32014-06-20 12:00:00 -0700374 msg, err := c.readHandshake()
375 if err != nil {
376 return err
377 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400378
379 if c.isDTLS {
380 helloVerifyRequest, ok := msg.(*helloVerifyRequestMsg)
381 if ok {
David Benjaminda4789e2016-10-31 19:23:34 -0400382 if helloVerifyRequest.vers != versionToWire(VersionTLS10, c.isDTLS) {
David Benjamin8bc38f52014-08-16 12:07:27 -0400383 // Per RFC 6347, the version field in
384 // HelloVerifyRequest SHOULD be always DTLS
385 // 1.0. Enforce this for testing purposes.
386 return errors.New("dtls: bad HelloVerifyRequest version")
387 }
388
David Benjamin83c0bc92014-08-04 01:23:53 -0400389 hello.raw = nil
390 hello.cookie = helloVerifyRequest.cookie
391 helloBytes = hello.marshal()
392 c.writeRecord(recordTypeHandshake, helloBytes)
David Benjamin582ba042016-07-07 12:33:25 -0700393 c.flushHandshake()
David Benjamin83c0bc92014-08-04 01:23:53 -0400394
David Benjamin83f90402015-01-27 01:09:43 -0500395 if err := c.simulatePacketLoss(nil); err != nil {
396 return err
397 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400398 msg, err = c.readHandshake()
399 if err != nil {
400 return err
401 }
402 }
403 }
404
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400405 var serverWireVersion uint16
Nick Harperdcfbc672016-07-16 17:47:31 +0200406 switch m := msg.(type) {
407 case *helloRetryRequestMsg:
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400408 serverWireVersion = m.vers
Nick Harperdcfbc672016-07-16 17:47:31 +0200409 case *serverHelloMsg:
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400410 serverWireVersion = m.vers
Nick Harperdcfbc672016-07-16 17:47:31 +0200411 default:
412 c.sendAlert(alertUnexpectedMessage)
413 return fmt.Errorf("tls: received unexpected message of type %T when waiting for HelloRetryRequest or ServerHello", msg)
414 }
415
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400416 serverVersion, ok := wireToVersion(serverWireVersion, c.isDTLS)
417 if ok {
Steven Valdezfdd10992016-09-15 16:27:05 -0400418 ok = c.config.isSupportedVersion(serverVersion, c.isDTLS)
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400419 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200420 if !ok {
421 c.sendAlert(alertProtocolVersion)
422 return fmt.Errorf("tls: server selected unsupported protocol version %x", c.vers)
423 }
Steven Valdezfdd10992016-09-15 16:27:05 -0400424 c.vers = serverVersion
Nick Harperdcfbc672016-07-16 17:47:31 +0200425 c.haveVers = true
426
427 helloRetryRequest, haveHelloRetryRequest := msg.(*helloRetryRequestMsg)
428 var secondHelloBytes []byte
429 if haveHelloRetryRequest {
David Benjamin3baa6e12016-10-07 21:10:38 -0400430 if len(helloRetryRequest.cookie) > 0 {
431 hello.tls13Cookie = helloRetryRequest.cookie
432 }
433
Steven Valdez5440fe02016-07-18 12:40:30 -0400434 if c.config.Bugs.MisinterpretHelloRetryRequestCurve != 0 {
David Benjamin3baa6e12016-10-07 21:10:38 -0400435 helloRetryRequest.hasSelectedGroup = true
Steven Valdez5440fe02016-07-18 12:40:30 -0400436 helloRetryRequest.selectedGroup = c.config.Bugs.MisinterpretHelloRetryRequestCurve
437 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400438 if helloRetryRequest.hasSelectedGroup {
439 var hrrCurveFound bool
440 group := helloRetryRequest.selectedGroup
441 for _, curveID := range hello.supportedCurves {
442 if group == curveID {
443 hrrCurveFound = true
444 break
445 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200446 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400447 if !hrrCurveFound || keyShares[group] != nil {
448 c.sendAlert(alertHandshakeFailure)
449 return errors.New("tls: received invalid HelloRetryRequest")
450 }
451 curve, ok := curveForCurveID(group)
452 if !ok {
453 return errors.New("tls: Unable to get curve requested in HelloRetryRequest")
454 }
455 publicKey, err := curve.offer(c.config.rand())
456 if err != nil {
457 return err
458 }
459 keyShares[group] = curve
Steven Valdeza833c352016-11-01 13:39:36 -0400460 hello.keyShares = []keyShareEntry{{
David Benjamin3baa6e12016-10-07 21:10:38 -0400461 group: group,
462 keyExchange: publicKey,
Steven Valdeza833c352016-11-01 13:39:36 -0400463 }}
Nick Harperdcfbc672016-07-16 17:47:31 +0200464 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200465
Steven Valdez5440fe02016-07-18 12:40:30 -0400466 if c.config.Bugs.SecondClientHelloMissingKeyShare {
467 hello.hasKeyShares = false
468 }
469
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500470 hello.hasEarlyData = c.config.Bugs.SendEarlyDataOnSecondClientHello
Nick Harperdcfbc672016-07-16 17:47:31 +0200471 hello.raw = nil
472
Steven Valdeza833c352016-11-01 13:39:36 -0400473 if len(hello.pskIdentities) > 0 {
474 generatePSKBinders(hello, pskCipherSuite, session.masterSecret, append(helloBytes, helloRetryRequest.marshal()...), c.config)
475 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200476 secondHelloBytes = hello.marshal()
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500477
478 if c.config.Bugs.InterleaveEarlyData {
479 c.sendFakeEarlyData(4)
480 c.writeRecord(recordTypeHandshake, secondHelloBytes[:16])
481 c.sendFakeEarlyData(4)
482 c.writeRecord(recordTypeHandshake, secondHelloBytes[16:])
483 } else {
484 c.writeRecord(recordTypeHandshake, secondHelloBytes)
485 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200486 c.flushHandshake()
487
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500488 if c.config.Bugs.SendEarlyDataOnSecondClientHello {
489 c.sendFakeEarlyData(4)
490 }
491
Nick Harperdcfbc672016-07-16 17:47:31 +0200492 msg, err = c.readHandshake()
493 if err != nil {
494 return err
495 }
496 }
497
Adam Langley95c29f32014-06-20 12:00:00 -0700498 serverHello, ok := msg.(*serverHelloMsg)
499 if !ok {
500 c.sendAlert(alertUnexpectedMessage)
501 return unexpectedMessageError(serverHello, msg)
502 }
503
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400504 if serverWireVersion != serverHello.vers {
Adam Langley95c29f32014-06-20 12:00:00 -0700505 c.sendAlert(alertProtocolVersion)
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400506 return fmt.Errorf("tls: server sent non-matching version %x vs %x", serverWireVersion, serverHello.vers)
Adam Langley95c29f32014-06-20 12:00:00 -0700507 }
Adam Langley95c29f32014-06-20 12:00:00 -0700508
Nick Harper85f20c22016-07-04 10:11:59 -0700509 // Check for downgrade signals in the server random, per
David Benjamina128a552016-10-13 14:26:33 -0400510 // draft-ietf-tls-tls13-16, section 4.1.3.
Nick Harper85f20c22016-07-04 10:11:59 -0700511 if c.vers <= VersionTLS12 && c.config.maxVersion(c.isDTLS) >= VersionTLS13 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400512 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS13) {
Nick Harper85f20c22016-07-04 10:11:59 -0700513 c.sendAlert(alertProtocolVersion)
514 return errors.New("tls: downgrade from TLS 1.3 detected")
515 }
516 }
517 if c.vers <= VersionTLS11 && c.config.maxVersion(c.isDTLS) >= VersionTLS12 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400518 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS12) {
Nick Harper85f20c22016-07-04 10:11:59 -0700519 c.sendAlert(alertProtocolVersion)
520 return errors.New("tls: downgrade from TLS 1.2 detected")
521 }
522 }
523
Nick Harper0b3625b2016-07-25 16:16:28 -0700524 suite := mutualCipherSuite(hello.cipherSuites, serverHello.cipherSuite)
Adam Langley95c29f32014-06-20 12:00:00 -0700525 if suite == nil {
526 c.sendAlert(alertHandshakeFailure)
527 return fmt.Errorf("tls: server selected an unsupported cipher suite")
528 }
529
David Benjamin3baa6e12016-10-07 21:10:38 -0400530 if haveHelloRetryRequest && helloRetryRequest.hasSelectedGroup && helloRetryRequest.selectedGroup != serverHello.keyShare.group {
Nick Harperdcfbc672016-07-16 17:47:31 +0200531 c.sendAlert(alertHandshakeFailure)
532 return errors.New("tls: ServerHello parameters did not match HelloRetryRequest")
533 }
534
Adam Langley95c29f32014-06-20 12:00:00 -0700535 hs := &clientHandshakeState{
536 c: c,
537 serverHello: serverHello,
538 hello: hello,
539 suite: suite,
540 finishedHash: newFinishedHash(c.vers, suite),
Nick Harperb41d2e42016-07-01 17:50:32 -0400541 keyShares: keyShares,
Adam Langley95c29f32014-06-20 12:00:00 -0700542 session: session,
543 }
544
David Benjamin83c0bc92014-08-04 01:23:53 -0400545 hs.writeHash(helloBytes, hs.c.sendHandshakeSeq-1)
Nick Harperdcfbc672016-07-16 17:47:31 +0200546 if haveHelloRetryRequest {
547 hs.writeServerHash(helloRetryRequest.marshal())
548 hs.writeClientHash(secondHelloBytes)
549 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400550 hs.writeServerHash(hs.serverHello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700551
David Benjamin8d315d72016-07-18 01:03:18 +0200552 if c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -0400553 if err := hs.doTLS13Handshake(); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700554 return err
555 }
556 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400557 if c.config.Bugs.EarlyChangeCipherSpec > 0 {
558 hs.establishKeys()
559 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
560 }
561
562 if hs.serverHello.compressionMethod != compressionNone {
563 c.sendAlert(alertUnexpectedMessage)
564 return errors.New("tls: server selected unsupported compression format")
565 }
566
567 err = hs.processServerExtensions(&serverHello.extensions)
568 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700569 return err
570 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400571
572 isResume, err := hs.processServerHello()
573 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700574 return err
575 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400576
577 if isResume {
578 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
579 if err := hs.establishKeys(); err != nil {
580 return err
581 }
582 }
583 if err := hs.readSessionTicket(); err != nil {
584 return err
585 }
586 if err := hs.readFinished(c.firstFinished[:]); err != nil {
587 return err
588 }
589 if err := hs.sendFinished(nil, isResume); err != nil {
590 return err
591 }
592 } else {
593 if err := hs.doFullHandshake(); err != nil {
594 return err
595 }
596 if err := hs.establishKeys(); err != nil {
597 return err
598 }
599 if err := hs.sendFinished(c.firstFinished[:], isResume); err != nil {
600 return err
601 }
602 // Most retransmits are triggered by a timeout, but the final
603 // leg of the handshake is retransmited upon re-receiving a
604 // Finished.
605 if err := c.simulatePacketLoss(func() {
David Benjamin02edcd02016-07-27 17:40:37 -0400606 c.sendHandshakeSeq--
Nick Harperb41d2e42016-07-01 17:50:32 -0400607 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
608 c.flushHandshake()
609 }); err != nil {
610 return err
611 }
612 if err := hs.readSessionTicket(); err != nil {
613 return err
614 }
615 if err := hs.readFinished(nil); err != nil {
616 return err
617 }
Adam Langley95c29f32014-06-20 12:00:00 -0700618 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400619
620 if sessionCache != nil && hs.session != nil && session != hs.session {
621 if c.config.Bugs.RequireSessionTickets && len(hs.session.sessionTicket) == 0 {
622 return errors.New("tls: new session used session IDs instead of tickets")
623 }
624 sessionCache.Put(cacheKey, hs.session)
David Benjamin83f90402015-01-27 01:09:43 -0500625 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400626
627 c.didResume = isResume
David Benjamin97a0a082016-07-13 17:57:35 -0400628 c.exporterSecret = hs.masterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700629 }
630
Adam Langley95c29f32014-06-20 12:00:00 -0700631 c.handshakeComplete = true
David Benjaminc565ebb2015-04-03 04:06:36 -0400632 c.cipherSuite = suite
633 copy(c.clientRandom[:], hs.hello.random)
634 copy(c.serverRandom[:], hs.serverHello.random)
Paul Lietar4fac72e2015-09-09 13:44:55 +0100635
Adam Langley95c29f32014-06-20 12:00:00 -0700636 return nil
637}
638
Nick Harperb41d2e42016-07-01 17:50:32 -0400639func (hs *clientHandshakeState) doTLS13Handshake() error {
640 c := hs.c
641
642 // Once the PRF hash is known, TLS 1.3 does not require a handshake
643 // buffer.
644 hs.finishedHash.discardHandshakeBuffer()
645
646 zeroSecret := hs.finishedHash.zeroSecret()
647
648 // Resolve PSK and compute the early secret.
649 //
650 // TODO(davidben): This will need to be handled slightly earlier once
651 // 0-RTT is implemented.
Steven Valdez803c77a2016-09-06 14:13:43 -0400652 if hs.serverHello.hasPSKIdentity {
Nick Harper0b3625b2016-07-25 16:16:28 -0700653 // We send at most one PSK identity.
654 if hs.session == nil || hs.serverHello.pskIdentity != 0 {
655 c.sendAlert(alertUnknownPSKIdentity)
656 return errors.New("tls: server sent unknown PSK identity")
657 }
David Benjamin2b02f4b2016-11-16 16:11:47 +0900658 sessionCipher := cipherSuiteFromID(hs.session.cipherSuite)
659 if sessionCipher == nil || sessionCipher.hash() != hs.suite.hash() {
Nick Harper0b3625b2016-07-25 16:16:28 -0700660 c.sendAlert(alertHandshakeFailure)
David Benjamin2b02f4b2016-11-16 16:11:47 +0900661 return errors.New("tls: server resumed an invalid session for the cipher suite")
Nick Harper0b3625b2016-07-25 16:16:28 -0700662 }
David Benjamin48891ad2016-12-04 00:02:43 -0500663 hs.finishedHash.addEntropy(hs.session.masterSecret)
Nick Harper0b3625b2016-07-25 16:16:28 -0700664 c.didResume = true
Nick Harperb41d2e42016-07-01 17:50:32 -0400665 } else {
David Benjamin48891ad2016-12-04 00:02:43 -0500666 hs.finishedHash.addEntropy(zeroSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400667 }
668
Steven Valdeza833c352016-11-01 13:39:36 -0400669 if !hs.serverHello.hasKeyShare {
670 c.sendAlert(alertUnsupportedExtension)
671 return errors.New("tls: server omitted KeyShare on resumption.")
672 }
673
Nick Harperb41d2e42016-07-01 17:50:32 -0400674 // Resolve ECDHE and compute the handshake secret.
Steven Valdez803c77a2016-09-06 14:13:43 -0400675 if !c.config.Bugs.MissingKeyShare && !c.config.Bugs.SecondClientHelloMissingKeyShare {
Nick Harperb41d2e42016-07-01 17:50:32 -0400676 curve, ok := hs.keyShares[hs.serverHello.keyShare.group]
677 if !ok {
678 c.sendAlert(alertHandshakeFailure)
679 return errors.New("tls: server selected an unsupported group")
680 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400681 c.curveID = hs.serverHello.keyShare.group
Nick Harperb41d2e42016-07-01 17:50:32 -0400682
David Benjamin48891ad2016-12-04 00:02:43 -0500683 ecdheSecret, err := curve.finish(hs.serverHello.keyShare.keyExchange)
Nick Harperb41d2e42016-07-01 17:50:32 -0400684 if err != nil {
685 return err
686 }
David Benjamin48891ad2016-12-04 00:02:43 -0500687 hs.finishedHash.addEntropy(ecdheSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400688 } else {
David Benjamin48891ad2016-12-04 00:02:43 -0500689 hs.finishedHash.addEntropy(zeroSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400690 }
691
David Benjamin6f600d62016-12-21 16:06:54 -0500692 if hs.serverHello.shortHeader && !hs.hello.shortHeaderSupported {
693 return errors.New("tls: server sent unsolicited short header extension")
694 }
695
696 if hs.serverHello.shortHeader && hs.hello.hasEarlyData {
697 return errors.New("tls: server sent short header extension in response to early data")
698 }
699
700 if hs.serverHello.shortHeader {
701 c.setShortHeader()
702 }
703
Nick Harperb41d2e42016-07-01 17:50:32 -0400704 // Switch to handshake traffic keys.
David Benjamin48891ad2016-12-04 00:02:43 -0500705 clientHandshakeTrafficSecret := hs.finishedHash.deriveSecret(clientHandshakeTrafficLabel)
Steven Valdeza833c352016-11-01 13:39:36 -0400706 c.out.useTrafficSecret(c.vers, hs.suite, clientHandshakeTrafficSecret, clientWrite)
David Benjamin48891ad2016-12-04 00:02:43 -0500707 serverHandshakeTrafficSecret := hs.finishedHash.deriveSecret(serverHandshakeTrafficLabel)
Steven Valdeza833c352016-11-01 13:39:36 -0400708 c.in.useTrafficSecret(c.vers, hs.suite, serverHandshakeTrafficSecret, serverWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -0400709
710 msg, err := c.readHandshake()
711 if err != nil {
712 return err
713 }
714
715 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
716 if !ok {
717 c.sendAlert(alertUnexpectedMessage)
718 return unexpectedMessageError(encryptedExtensions, msg)
719 }
720 hs.writeServerHash(encryptedExtensions.marshal())
721
722 err = hs.processServerExtensions(&encryptedExtensions.extensions)
723 if err != nil {
724 return err
725 }
726
727 var chainToSend *Certificate
David Benjamin8d343b42016-07-09 14:26:01 -0700728 var certReq *certificateRequestMsg
Steven Valdeza833c352016-11-01 13:39:36 -0400729 if c.didResume {
Nick Harper0b3625b2016-07-25 16:16:28 -0700730 // Copy over authentication from the session.
731 c.peerCertificates = hs.session.serverCertificates
732 c.sctList = hs.session.sctList
733 c.ocspResponse = hs.session.ocspResponse
David Benjamin44b33bc2016-07-01 22:40:23 -0400734 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400735 msg, err := c.readHandshake()
736 if err != nil {
737 return err
738 }
739
David Benjamin8d343b42016-07-09 14:26:01 -0700740 var ok bool
741 certReq, ok = msg.(*certificateRequestMsg)
Nick Harperb41d2e42016-07-01 17:50:32 -0400742 if ok {
David Benjamin8a8349b2016-08-18 02:32:23 -0400743 if len(certReq.requestContext) != 0 {
744 return errors.New("tls: non-empty certificate request context sent in handshake")
745 }
746
David Benjaminb62d2872016-07-18 14:55:02 +0200747 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
748 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
749 }
750
Nick Harperb41d2e42016-07-01 17:50:32 -0400751 hs.writeServerHash(certReq.marshal())
Nick Harperb41d2e42016-07-01 17:50:32 -0400752
753 chainToSend, err = selectClientCertificate(c, certReq)
754 if err != nil {
755 return err
756 }
757
758 msg, err = c.readHandshake()
759 if err != nil {
760 return err
761 }
762 }
763
764 certMsg, ok := msg.(*certificateMsg)
765 if !ok {
766 c.sendAlert(alertUnexpectedMessage)
767 return unexpectedMessageError(certMsg, msg)
768 }
769 hs.writeServerHash(certMsg.marshal())
770
David Benjamin53210cb2016-11-16 09:01:48 +0900771 // Check for unsolicited extensions.
772 for i, cert := range certMsg.certificates {
773 if c.config.Bugs.NoOCSPStapling && cert.ocspResponse != nil {
774 c.sendAlert(alertUnsupportedExtension)
775 return errors.New("tls: unexpected OCSP response in the server certificate")
776 }
777 if c.config.Bugs.NoSignedCertificateTimestamps && cert.sctList != nil {
778 c.sendAlert(alertUnsupportedExtension)
779 return errors.New("tls: unexpected SCT list in the server certificate")
780 }
781 if i > 0 && c.config.Bugs.ExpectNoExtensionsOnIntermediate && (cert.ocspResponse != nil || cert.sctList != nil) {
782 c.sendAlert(alertUnsupportedExtension)
783 return errors.New("tls: unexpected extensions in the server certificate")
784 }
785 }
786
Nick Harperb41d2e42016-07-01 17:50:32 -0400787 if err := hs.verifyCertificates(certMsg); err != nil {
788 return err
789 }
790 leaf := c.peerCertificates[0]
Steven Valdeza833c352016-11-01 13:39:36 -0400791 c.ocspResponse = certMsg.certificates[0].ocspResponse
792 c.sctList = certMsg.certificates[0].sctList
793
Nick Harperb41d2e42016-07-01 17:50:32 -0400794 msg, err = c.readHandshake()
795 if err != nil {
796 return err
797 }
798 certVerifyMsg, ok := msg.(*certificateVerifyMsg)
799 if !ok {
800 c.sendAlert(alertUnexpectedMessage)
801 return unexpectedMessageError(certVerifyMsg, msg)
802 }
803
David Benjaminf74ec792016-07-13 21:18:49 -0400804 c.peerSignatureAlgorithm = certVerifyMsg.signatureAlgorithm
Nick Harperb41d2e42016-07-01 17:50:32 -0400805 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
David Benjamin1fb125c2016-07-08 18:52:12 -0700806 err = verifyMessage(c.vers, leaf.PublicKey, c.config, certVerifyMsg.signatureAlgorithm, input, certVerifyMsg.signature)
Nick Harperb41d2e42016-07-01 17:50:32 -0400807 if err != nil {
808 return err
809 }
810
811 hs.writeServerHash(certVerifyMsg.marshal())
812 }
813
814 msg, err = c.readHandshake()
815 if err != nil {
816 return err
817 }
818 serverFinished, ok := msg.(*finishedMsg)
819 if !ok {
820 c.sendAlert(alertUnexpectedMessage)
821 return unexpectedMessageError(serverFinished, msg)
822 }
823
Steven Valdezc4aa7272016-10-03 12:25:56 -0400824 verify := hs.finishedHash.serverSum(serverHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400825 if len(verify) != len(serverFinished.verifyData) ||
826 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
827 c.sendAlert(alertHandshakeFailure)
828 return errors.New("tls: server's Finished message was incorrect")
829 }
830
831 hs.writeServerHash(serverFinished.marshal())
832
833 // The various secrets do not incorporate the client's final leg, so
834 // derive them now before updating the handshake context.
David Benjamin48891ad2016-12-04 00:02:43 -0500835 hs.finishedHash.addEntropy(zeroSecret)
836 clientTrafficSecret := hs.finishedHash.deriveSecret(clientApplicationTrafficLabel)
837 serverTrafficSecret := hs.finishedHash.deriveSecret(serverApplicationTrafficLabel)
Nick Harper7cd0a972016-12-02 11:08:40 -0800838 c.in.useTrafficSecret(c.vers, hs.suite, serverTrafficSecret, serverWrite)
839
840 // If we're expecting 0.5-RTT messages from the server, read them
841 // now.
842 for _, expectedMsg := range c.config.Bugs.ExpectHalfRTTData {
843 if err := c.readRecord(recordTypeApplicationData); err != nil {
844 return err
845 }
846 if !bytes.Equal(c.input.data[c.input.off:], expectedMsg) {
847 return errors.New("ExpectHalfRTTData: did not get expected message")
848 }
849 c.in.freeBlock(c.input)
850 c.input = nil
851 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400852
Steven Valdez0ee2e112016-07-15 06:51:15 -0400853 if certReq != nil && !c.config.Bugs.SkipClientCertificate {
David Benjamin8d343b42016-07-09 14:26:01 -0700854 certMsg := &certificateMsg{
855 hasRequestContext: true,
856 requestContext: certReq.requestContext,
857 }
858 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -0400859 for _, certData := range chainToSend.Certificate {
860 certMsg.certificates = append(certMsg.certificates, certificateEntry{
861 data: certData,
862 extraExtension: c.config.Bugs.SendExtensionOnCertificate,
863 })
864 }
David Benjamin8d343b42016-07-09 14:26:01 -0700865 }
866 hs.writeClientHash(certMsg.marshal())
867 c.writeRecord(recordTypeHandshake, certMsg.marshal())
868
869 if chainToSend != nil {
870 certVerify := &certificateVerifyMsg{
871 hasSignatureAlgorithm: true,
872 }
873
874 // Determine the hash to sign.
875 privKey := chainToSend.PrivateKey
876
877 var err error
878 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
879 if err != nil {
880 c.sendAlert(alertInternalError)
881 return err
882 }
883
884 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
885 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
886 if err != nil {
887 c.sendAlert(alertInternalError)
888 return err
889 }
Steven Valdez0ee2e112016-07-15 06:51:15 -0400890 if c.config.Bugs.SendSignatureAlgorithm != 0 {
891 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
892 }
David Benjamin8d343b42016-07-09 14:26:01 -0700893
894 hs.writeClientHash(certVerify.marshal())
895 c.writeRecord(recordTypeHandshake, certVerify.marshal())
896 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400897 }
898
Nick Harper60a85cb2016-09-23 16:25:11 -0700899 if encryptedExtensions.extensions.channelIDRequested {
900 channelIDHash := crypto.SHA256.New()
901 channelIDHash.Write(hs.finishedHash.certificateVerifyInput(channelIDContextTLS13))
902 channelIDMsgBytes, err := hs.writeChannelIDMessage(channelIDHash.Sum(nil))
903 if err != nil {
904 return err
905 }
906 hs.writeClientHash(channelIDMsgBytes)
907 c.writeRecord(recordTypeHandshake, channelIDMsgBytes)
908 }
909
Nick Harperb41d2e42016-07-01 17:50:32 -0400910 // Send a client Finished message.
911 finished := new(finishedMsg)
Steven Valdezc4aa7272016-10-03 12:25:56 -0400912 finished.verifyData = hs.finishedHash.clientSum(clientHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400913 if c.config.Bugs.BadFinished {
914 finished.verifyData[0]++
915 }
David Benjamin97a0a082016-07-13 17:57:35 -0400916 hs.writeClientHash(finished.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400917 if c.config.Bugs.PartialClientFinishedWithClientHello {
918 // The first byte has already been sent.
919 c.writeRecord(recordTypeHandshake, finished.marshal()[1:])
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500920 } else if c.config.Bugs.InterleaveEarlyData {
921 finishedBytes := finished.marshal()
922 c.sendFakeEarlyData(4)
923 c.writeRecord(recordTypeHandshake, finishedBytes[:1])
924 c.sendFakeEarlyData(4)
925 c.writeRecord(recordTypeHandshake, finishedBytes[1:])
David Benjamin7964b182016-07-14 23:36:30 -0400926 } else {
927 c.writeRecord(recordTypeHandshake, finished.marshal())
928 }
David Benjamin02edcd02016-07-27 17:40:37 -0400929 if c.config.Bugs.SendExtraFinished {
930 c.writeRecord(recordTypeHandshake, finished.marshal())
931 }
David Benjaminee51a222016-07-07 18:34:12 -0700932 c.flushHandshake()
Nick Harperb41d2e42016-07-01 17:50:32 -0400933
934 // Switch to application data keys.
Steven Valdeza833c352016-11-01 13:39:36 -0400935 c.out.useTrafficSecret(c.vers, hs.suite, clientTrafficSecret, clientWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -0400936
David Benjamin48891ad2016-12-04 00:02:43 -0500937 c.exporterSecret = hs.finishedHash.deriveSecret(exporterLabel)
938 c.resumptionSecret = hs.finishedHash.deriveSecret(resumptionLabel)
Nick Harperb41d2e42016-07-01 17:50:32 -0400939 return nil
940}
941
Adam Langley95c29f32014-06-20 12:00:00 -0700942func (hs *clientHandshakeState) doFullHandshake() error {
943 c := hs.c
944
David Benjamin48cae082014-10-27 01:06:24 -0400945 var leaf *x509.Certificate
946 if hs.suite.flags&suitePSK == 0 {
947 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700948 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700949 return err
950 }
Adam Langley95c29f32014-06-20 12:00:00 -0700951
David Benjamin48cae082014-10-27 01:06:24 -0400952 certMsg, ok := msg.(*certificateMsg)
David Benjamin75051442016-07-01 18:58:51 -0400953 if !ok {
David Benjamin48cae082014-10-27 01:06:24 -0400954 c.sendAlert(alertUnexpectedMessage)
955 return unexpectedMessageError(certMsg, msg)
956 }
957 hs.writeServerHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700958
David Benjamin75051442016-07-01 18:58:51 -0400959 if err := hs.verifyCertificates(certMsg); err != nil {
960 return err
David Benjamin48cae082014-10-27 01:06:24 -0400961 }
David Benjamin75051442016-07-01 18:58:51 -0400962 leaf = c.peerCertificates[0]
David Benjamin48cae082014-10-27 01:06:24 -0400963 }
Adam Langley95c29f32014-06-20 12:00:00 -0700964
Nick Harperb3d51be2016-07-01 11:43:18 -0400965 if hs.serverHello.extensions.ocspStapling {
David Benjamin48cae082014-10-27 01:06:24 -0400966 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700967 if err != nil {
968 return err
969 }
970 cs, ok := msg.(*certificateStatusMsg)
971 if !ok {
972 c.sendAlert(alertUnexpectedMessage)
973 return unexpectedMessageError(cs, msg)
974 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400975 hs.writeServerHash(cs.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700976
977 if cs.statusType == statusTypeOCSP {
978 c.ocspResponse = cs.response
979 }
980 }
981
David Benjamin48cae082014-10-27 01:06:24 -0400982 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700983 if err != nil {
984 return err
985 }
986
987 keyAgreement := hs.suite.ka(c.vers)
988
989 skx, ok := msg.(*serverKeyExchangeMsg)
990 if ok {
David Benjamin83c0bc92014-08-04 01:23:53 -0400991 hs.writeServerHash(skx.marshal())
David Benjamin48cae082014-10-27 01:06:24 -0400992 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, leaf, skx)
Adam Langley95c29f32014-06-20 12:00:00 -0700993 if err != nil {
994 c.sendAlert(alertUnexpectedMessage)
995 return err
996 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400997 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
998 c.curveID = ecdhe.curveID
999 }
Adam Langley95c29f32014-06-20 12:00:00 -07001000
Nick Harper60edffd2016-06-21 15:19:24 -07001001 c.peerSignatureAlgorithm = keyAgreement.peerSignatureAlgorithm()
1002
Adam Langley95c29f32014-06-20 12:00:00 -07001003 msg, err = c.readHandshake()
1004 if err != nil {
1005 return err
1006 }
1007 }
1008
1009 var chainToSend *Certificate
1010 var certRequested bool
1011 certReq, ok := msg.(*certificateRequestMsg)
1012 if ok {
1013 certRequested = true
David Benjamin7a41d372016-07-09 11:21:54 -07001014 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
1015 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
1016 }
Adam Langley95c29f32014-06-20 12:00:00 -07001017
David Benjamin83c0bc92014-08-04 01:23:53 -04001018 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001019
David Benjamina6f82632016-07-01 18:44:02 -04001020 chainToSend, err = selectClientCertificate(c, certReq)
1021 if err != nil {
1022 return err
Adam Langley95c29f32014-06-20 12:00:00 -07001023 }
1024
1025 msg, err = c.readHandshake()
1026 if err != nil {
1027 return err
1028 }
1029 }
1030
1031 shd, ok := msg.(*serverHelloDoneMsg)
1032 if !ok {
1033 c.sendAlert(alertUnexpectedMessage)
1034 return unexpectedMessageError(shd, msg)
1035 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001036 hs.writeServerHash(shd.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001037
1038 // If the server requested a certificate then we have to send a
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001039 // Certificate message in TLS, even if it's empty because we don't have
1040 // a certificate to send. In SSL 3.0, skip the message and send a
1041 // no_certificate warning alert.
Adam Langley95c29f32014-06-20 12:00:00 -07001042 if certRequested {
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001043 if c.vers == VersionSSL30 && chainToSend == nil {
David Benjamin053fee92017-01-02 08:30:36 -05001044 c.sendAlert(alertNoCertificate)
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001045 } else if !c.config.Bugs.SkipClientCertificate {
1046 certMsg := new(certificateMsg)
1047 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -04001048 for _, certData := range chainToSend.Certificate {
1049 certMsg.certificates = append(certMsg.certificates, certificateEntry{
1050 data: certData,
1051 })
1052 }
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001053 }
1054 hs.writeClientHash(certMsg.marshal())
1055 c.writeRecord(recordTypeHandshake, certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001056 }
Adam Langley95c29f32014-06-20 12:00:00 -07001057 }
1058
David Benjamin48cae082014-10-27 01:06:24 -04001059 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, leaf)
Adam Langley95c29f32014-06-20 12:00:00 -07001060 if err != nil {
1061 c.sendAlert(alertInternalError)
1062 return err
1063 }
1064 if ckx != nil {
David Benjaminf3ec83d2014-07-21 22:42:34 -04001065 if c.config.Bugs.EarlyChangeCipherSpec < 2 {
David Benjamin83c0bc92014-08-04 01:23:53 -04001066 hs.writeClientHash(ckx.marshal())
David Benjaminf3ec83d2014-07-21 22:42:34 -04001067 }
Adam Langley95c29f32014-06-20 12:00:00 -07001068 c.writeRecord(recordTypeHandshake, ckx.marshal())
1069 }
1070
Nick Harperb3d51be2016-07-01 11:43:18 -04001071 if hs.serverHello.extensions.extendedMasterSecret && c.vers >= VersionTLS10 {
Adam Langley75712922014-10-10 16:23:43 -07001072 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1073 c.extendedMasterSecret = true
1074 } else {
1075 if c.config.Bugs.RequireExtendedMasterSecret {
1076 return errors.New("tls: extended master secret required but not supported by peer")
1077 }
1078 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
1079 }
David Benjamine098ec22014-08-27 23:13:20 -04001080
Adam Langley95c29f32014-06-20 12:00:00 -07001081 if chainToSend != nil {
Adam Langley95c29f32014-06-20 12:00:00 -07001082 certVerify := &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001083 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001084 }
1085
David Benjamin72dc7832015-03-16 17:49:43 -04001086 // Determine the hash to sign.
Nick Harper60edffd2016-06-21 15:19:24 -07001087 privKey := c.config.Certificates[0].PrivateKey
David Benjamin72dc7832015-03-16 17:49:43 -04001088
Nick Harper60edffd2016-06-21 15:19:24 -07001089 if certVerify.hasSignatureAlgorithm {
David Benjamin0a8deb22016-07-09 21:02:01 -07001090 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
Nick Harper60edffd2016-06-21 15:19:24 -07001091 if err != nil {
1092 c.sendAlert(alertInternalError)
1093 return err
Adam Langley95c29f32014-06-20 12:00:00 -07001094 }
Nick Harper60edffd2016-06-21 15:19:24 -07001095 }
1096
1097 if c.vers > VersionSSL30 {
David Benjamin5208fd42016-07-13 21:43:25 -04001098 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, hs.finishedHash.buffer)
David Benjamina95e9f32016-07-08 16:28:04 -07001099 if err == nil && c.config.Bugs.SendSignatureAlgorithm != 0 {
1100 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
1101 }
Nick Harper60edffd2016-06-21 15:19:24 -07001102 } else {
1103 // SSL 3.0's client certificate construction is
1104 // incompatible with signatureAlgorithm.
1105 rsaKey, ok := privKey.(*rsa.PrivateKey)
1106 if !ok {
1107 err = errors.New("unsupported signature type for client certificate")
1108 } else {
1109 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
David Benjamin5208fd42016-07-13 21:43:25 -04001110 if c.config.Bugs.InvalidSignature {
Nick Harper60edffd2016-06-21 15:19:24 -07001111 digest[0] ^= 0x80
1112 }
1113 certVerify.signature, err = rsa.SignPKCS1v15(c.config.rand(), rsaKey, crypto.MD5SHA1, digest)
1114 }
Adam Langley95c29f32014-06-20 12:00:00 -07001115 }
1116 if err != nil {
1117 c.sendAlert(alertInternalError)
1118 return errors.New("tls: failed to sign handshake with client certificate: " + err.Error())
1119 }
Adam Langley95c29f32014-06-20 12:00:00 -07001120
David Benjamin83c0bc92014-08-04 01:23:53 -04001121 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001122 c.writeRecord(recordTypeHandshake, certVerify.marshal())
1123 }
David Benjamin82261be2016-07-07 14:32:50 -07001124 // flushHandshake will be called in sendFinished.
Adam Langley95c29f32014-06-20 12:00:00 -07001125
David Benjamine098ec22014-08-27 23:13:20 -04001126 hs.finishedHash.discardHandshakeBuffer()
1127
Adam Langley95c29f32014-06-20 12:00:00 -07001128 return nil
1129}
1130
David Benjamin75051442016-07-01 18:58:51 -04001131func (hs *clientHandshakeState) verifyCertificates(certMsg *certificateMsg) error {
1132 c := hs.c
1133
1134 if len(certMsg.certificates) == 0 {
1135 c.sendAlert(alertIllegalParameter)
1136 return errors.New("tls: no certificates sent")
1137 }
1138
1139 certs := make([]*x509.Certificate, len(certMsg.certificates))
Steven Valdeza833c352016-11-01 13:39:36 -04001140 for i, certEntry := range certMsg.certificates {
1141 cert, err := x509.ParseCertificate(certEntry.data)
David Benjamin75051442016-07-01 18:58:51 -04001142 if err != nil {
1143 c.sendAlert(alertBadCertificate)
1144 return errors.New("tls: failed to parse certificate from server: " + err.Error())
1145 }
1146 certs[i] = cert
1147 }
1148
1149 if !c.config.InsecureSkipVerify {
1150 opts := x509.VerifyOptions{
1151 Roots: c.config.RootCAs,
1152 CurrentTime: c.config.time(),
1153 DNSName: c.config.ServerName,
1154 Intermediates: x509.NewCertPool(),
1155 }
1156
1157 for i, cert := range certs {
1158 if i == 0 {
1159 continue
1160 }
1161 opts.Intermediates.AddCert(cert)
1162 }
1163 var err error
1164 c.verifiedChains, err = certs[0].Verify(opts)
1165 if err != nil {
1166 c.sendAlert(alertBadCertificate)
1167 return err
1168 }
1169 }
1170
1171 switch certs[0].PublicKey.(type) {
1172 case *rsa.PublicKey, *ecdsa.PublicKey:
1173 break
1174 default:
1175 c.sendAlert(alertUnsupportedCertificate)
1176 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
1177 }
1178
1179 c.peerCertificates = certs
1180 return nil
1181}
1182
Adam Langley95c29f32014-06-20 12:00:00 -07001183func (hs *clientHandshakeState) establishKeys() error {
1184 c := hs.c
1185
1186 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001187 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 -07001188 var clientCipher, serverCipher interface{}
1189 var clientHash, serverHash macFunction
1190 if hs.suite.cipher != nil {
1191 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
1192 clientHash = hs.suite.mac(c.vers, clientMAC)
1193 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
1194 serverHash = hs.suite.mac(c.vers, serverMAC)
1195 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001196 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1197 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001198 }
1199
1200 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
1201 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
1202 return nil
1203}
1204
David Benjamin75101402016-07-01 13:40:23 -04001205func (hs *clientHandshakeState) processServerExtensions(serverExtensions *serverExtensions) error {
1206 c := hs.c
1207
David Benjamin8d315d72016-07-18 01:03:18 +02001208 if c.vers < VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001209 if c.config.Bugs.RequireRenegotiationInfo && serverExtensions.secureRenegotiation == nil {
1210 return errors.New("tls: renegotiation extension missing")
1211 }
David Benjamin75101402016-07-01 13:40:23 -04001212
Nick Harperb41d2e42016-07-01 17:50:32 -04001213 if len(c.clientVerify) > 0 && !c.noRenegotiationInfo() {
1214 var expectedRenegInfo []byte
1215 expectedRenegInfo = append(expectedRenegInfo, c.clientVerify...)
1216 expectedRenegInfo = append(expectedRenegInfo, c.serverVerify...)
1217 if !bytes.Equal(serverExtensions.secureRenegotiation, expectedRenegInfo) {
1218 c.sendAlert(alertHandshakeFailure)
1219 return fmt.Errorf("tls: renegotiation mismatch")
1220 }
David Benjamin75101402016-07-01 13:40:23 -04001221 }
David Benjamincea0ab42016-07-14 12:33:14 -04001222 } else if serverExtensions.secureRenegotiation != nil {
1223 return errors.New("tls: renegotiation info sent in TLS 1.3")
David Benjamin75101402016-07-01 13:40:23 -04001224 }
1225
1226 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
1227 if serverExtensions.customExtension != *expected {
1228 return fmt.Errorf("tls: bad custom extension contents %q", serverExtensions.customExtension)
1229 }
1230 }
1231
1232 clientDidNPN := hs.hello.nextProtoNeg
1233 clientDidALPN := len(hs.hello.alpnProtocols) > 0
1234 serverHasNPN := serverExtensions.nextProtoNeg
1235 serverHasALPN := len(serverExtensions.alpnProtocol) > 0
1236
1237 if !clientDidNPN && serverHasNPN {
1238 c.sendAlert(alertHandshakeFailure)
1239 return errors.New("server advertised unrequested NPN extension")
1240 }
1241
1242 if !clientDidALPN && serverHasALPN {
1243 c.sendAlert(alertHandshakeFailure)
1244 return errors.New("server advertised unrequested ALPN extension")
1245 }
1246
1247 if serverHasNPN && serverHasALPN {
1248 c.sendAlert(alertHandshakeFailure)
1249 return errors.New("server advertised both NPN and ALPN extensions")
1250 }
1251
1252 if serverHasALPN {
1253 c.clientProtocol = serverExtensions.alpnProtocol
1254 c.clientProtocolFallback = false
1255 c.usedALPN = true
1256 }
1257
David Benjamin8d315d72016-07-18 01:03:18 +02001258 if serverHasNPN && c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001259 c.sendAlert(alertHandshakeFailure)
1260 return errors.New("server advertised NPN over TLS 1.3")
1261 }
1262
David Benjamin75101402016-07-01 13:40:23 -04001263 if !hs.hello.channelIDSupported && serverExtensions.channelIDRequested {
1264 c.sendAlert(alertHandshakeFailure)
1265 return errors.New("server advertised unrequested Channel ID extension")
1266 }
1267
David Benjamin8d315d72016-07-18 01:03:18 +02001268 if serverExtensions.extendedMasterSecret && c.vers >= VersionTLS13 {
David Benjamine9077652016-07-13 21:02:08 -04001269 return errors.New("tls: server advertised extended master secret over TLS 1.3")
1270 }
1271
David Benjamin8d315d72016-07-18 01:03:18 +02001272 if serverExtensions.ticketSupported && c.vers >= VersionTLS13 {
Steven Valdez143e8b32016-07-11 13:19:03 -04001273 return errors.New("tls: server advertised ticket extension over TLS 1.3")
1274 }
1275
Steven Valdeza833c352016-11-01 13:39:36 -04001276 if serverExtensions.ocspStapling && c.vers >= VersionTLS13 {
1277 return errors.New("tls: server advertised OCSP in ServerHello over TLS 1.3")
1278 }
1279
David Benjamin53210cb2016-11-16 09:01:48 +09001280 if serverExtensions.ocspStapling && c.config.Bugs.NoOCSPStapling {
1281 return errors.New("tls: server advertised unrequested OCSP extension")
1282 }
1283
Steven Valdeza833c352016-11-01 13:39:36 -04001284 if len(serverExtensions.sctList) > 0 && c.vers >= VersionTLS13 {
1285 return errors.New("tls: server advertised SCTs in ServerHello over TLS 1.3")
1286 }
1287
David Benjamin53210cb2016-11-16 09:01:48 +09001288 if len(serverExtensions.sctList) > 0 && c.config.Bugs.NoSignedCertificateTimestamps {
1289 return errors.New("tls: server advertised unrequested SCTs")
1290 }
1291
David Benjamin75101402016-07-01 13:40:23 -04001292 if serverExtensions.srtpProtectionProfile != 0 {
1293 if serverExtensions.srtpMasterKeyIdentifier != "" {
1294 return errors.New("tls: server selected SRTP MKI value")
1295 }
1296
1297 found := false
1298 for _, p := range c.config.SRTPProtectionProfiles {
1299 if p == serverExtensions.srtpProtectionProfile {
1300 found = true
1301 break
1302 }
1303 }
1304 if !found {
1305 return errors.New("tls: server advertised unsupported SRTP profile")
1306 }
1307
1308 c.srtpProtectionProfile = serverExtensions.srtpProtectionProfile
1309 }
1310
1311 return nil
1312}
1313
Adam Langley95c29f32014-06-20 12:00:00 -07001314func (hs *clientHandshakeState) serverResumedSession() bool {
1315 // If the server responded with the same sessionId then it means the
1316 // sessionTicket is being used to resume a TLS session.
1317 return hs.session != nil && hs.hello.sessionId != nil &&
1318 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
1319}
1320
1321func (hs *clientHandshakeState) processServerHello() (bool, error) {
1322 c := hs.c
1323
David Benjamin6f600d62016-12-21 16:06:54 -05001324 if hs.serverHello.shortHeader {
1325 return false, errors.New("tls: short header extension sent before TLS 1.3")
1326 }
1327
Adam Langley95c29f32014-06-20 12:00:00 -07001328 if hs.serverResumedSession() {
David Benjamin4b27d9f2015-05-12 22:42:52 -04001329 // For test purposes, assert that the server never accepts the
1330 // resumption offer on renegotiation.
1331 if c.cipherSuite != nil && c.config.Bugs.FailIfResumeOnRenego {
1332 return false, errors.New("tls: server resumed session on renegotiation")
1333 }
1334
Nick Harperb3d51be2016-07-01 11:43:18 -04001335 if hs.serverHello.extensions.sctList != nil {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001336 return false, errors.New("tls: server sent SCT extension on session resumption")
1337 }
1338
Nick Harperb3d51be2016-07-01 11:43:18 -04001339 if hs.serverHello.extensions.ocspStapling {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001340 return false, errors.New("tls: server sent OCSP extension on session resumption")
1341 }
1342
Adam Langley95c29f32014-06-20 12:00:00 -07001343 // Restore masterSecret and peerCerts from previous state
1344 hs.masterSecret = hs.session.masterSecret
1345 c.peerCertificates = hs.session.serverCertificates
Adam Langley75712922014-10-10 16:23:43 -07001346 c.extendedMasterSecret = hs.session.extendedMasterSecret
Paul Lietar62be8ac2015-09-16 10:03:30 +01001347 c.sctList = hs.session.sctList
1348 c.ocspResponse = hs.session.ocspResponse
David Benjamine098ec22014-08-27 23:13:20 -04001349 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001350 return true, nil
1351 }
Paul Lietar62be8ac2015-09-16 10:03:30 +01001352
Nick Harperb3d51be2016-07-01 11:43:18 -04001353 if hs.serverHello.extensions.sctList != nil {
1354 c.sctList = hs.serverHello.extensions.sctList
Paul Lietar62be8ac2015-09-16 10:03:30 +01001355 }
1356
Adam Langley95c29f32014-06-20 12:00:00 -07001357 return false, nil
1358}
1359
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001360func (hs *clientHandshakeState) readFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001361 c := hs.c
1362
1363 c.readRecord(recordTypeChangeCipherSpec)
1364 if err := c.in.error(); err != nil {
1365 return err
1366 }
1367
1368 msg, err := c.readHandshake()
1369 if err != nil {
1370 return err
1371 }
1372 serverFinished, ok := msg.(*finishedMsg)
1373 if !ok {
1374 c.sendAlert(alertUnexpectedMessage)
1375 return unexpectedMessageError(serverFinished, msg)
1376 }
1377
David Benjaminf3ec83d2014-07-21 22:42:34 -04001378 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
1379 verify := hs.finishedHash.serverSum(hs.masterSecret)
1380 if len(verify) != len(serverFinished.verifyData) ||
1381 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
1382 c.sendAlert(alertHandshakeFailure)
1383 return errors.New("tls: server's Finished message was incorrect")
1384 }
Adam Langley95c29f32014-06-20 12:00:00 -07001385 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001386 c.serverVerify = append(c.serverVerify[:0], serverFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001387 copy(out, serverFinished.verifyData)
David Benjamin83c0bc92014-08-04 01:23:53 -04001388 hs.writeServerHash(serverFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001389 return nil
1390}
1391
1392func (hs *clientHandshakeState) readSessionTicket() error {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001393 c := hs.c
1394
1395 // Create a session with no server identifier. Either a
1396 // session ID or session ticket will be attached.
1397 session := &ClientSessionState{
1398 vers: c.vers,
1399 cipherSuite: hs.suite.id,
1400 masterSecret: hs.masterSecret,
Nick Harperc9846112016-10-17 15:05:35 -07001401 handshakeHash: hs.finishedHash.Sum(),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001402 serverCertificates: c.peerCertificates,
Paul Lietar62be8ac2015-09-16 10:03:30 +01001403 sctList: c.sctList,
1404 ocspResponse: c.ocspResponse,
Nick Harper0b3625b2016-07-25 16:16:28 -07001405 ticketExpiration: c.config.time().Add(time.Duration(7 * 24 * time.Hour)),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001406 }
1407
Nick Harperb3d51be2016-07-01 11:43:18 -04001408 if !hs.serverHello.extensions.ticketSupported {
David Benjamind98452d2015-06-16 14:16:23 -04001409 if c.config.Bugs.ExpectNewTicket {
1410 return errors.New("tls: expected new ticket")
1411 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001412 if hs.session == nil && len(hs.serverHello.sessionId) > 0 {
1413 session.sessionId = hs.serverHello.sessionId
1414 hs.session = session
1415 }
Adam Langley95c29f32014-06-20 12:00:00 -07001416 return nil
1417 }
1418
David Benjaminc7ce9772015-10-09 19:32:41 -04001419 if c.vers == VersionSSL30 {
1420 return errors.New("tls: negotiated session tickets in SSL 3.0")
1421 }
1422
Adam Langley95c29f32014-06-20 12:00:00 -07001423 msg, err := c.readHandshake()
1424 if err != nil {
1425 return err
1426 }
1427 sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
1428 if !ok {
1429 c.sendAlert(alertUnexpectedMessage)
1430 return unexpectedMessageError(sessionTicketMsg, msg)
1431 }
Adam Langley95c29f32014-06-20 12:00:00 -07001432
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001433 session.sessionTicket = sessionTicketMsg.ticket
1434 hs.session = session
Adam Langley95c29f32014-06-20 12:00:00 -07001435
David Benjamind30a9902014-08-24 01:44:23 -04001436 hs.writeServerHash(sessionTicketMsg.marshal())
1437
Adam Langley95c29f32014-06-20 12:00:00 -07001438 return nil
1439}
1440
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001441func (hs *clientHandshakeState) sendFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001442 c := hs.c
1443
David Benjamin0b8d5da2016-07-15 00:39:56 -04001444 var postCCSMsgs [][]byte
David Benjamin83c0bc92014-08-04 01:23:53 -04001445 seqno := hs.c.sendHandshakeSeq
Nick Harperb3d51be2016-07-01 11:43:18 -04001446 if hs.serverHello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001447 nextProto := new(nextProtoMsg)
Nick Harperb3d51be2016-07-01 11:43:18 -04001448 proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.extensions.nextProtos)
Adam Langley95c29f32014-06-20 12:00:00 -07001449 nextProto.proto = proto
1450 c.clientProtocol = proto
1451 c.clientProtocolFallback = fallback
1452
David Benjamin86271ee2014-07-21 16:14:03 -04001453 nextProtoBytes := nextProto.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -04001454 hs.writeHash(nextProtoBytes, seqno)
1455 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001456 postCCSMsgs = append(postCCSMsgs, nextProtoBytes)
Adam Langley95c29f32014-06-20 12:00:00 -07001457 }
1458
Nick Harperb3d51be2016-07-01 11:43:18 -04001459 if hs.serverHello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001460 var resumeHash []byte
1461 if isResume {
1462 resumeHash = hs.session.handshakeHash
1463 }
Nick Harper60a85cb2016-09-23 16:25:11 -07001464 channelIDMsgBytes, err := hs.writeChannelIDMessage(hs.finishedHash.hashForChannelID(resumeHash))
David Benjamind30a9902014-08-24 01:44:23 -04001465 if err != nil {
1466 return err
1467 }
David Benjamin24599a82016-06-30 18:56:53 -04001468 hs.writeHash(channelIDMsgBytes, seqno)
David Benjamind30a9902014-08-24 01:44:23 -04001469 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001470 postCCSMsgs = append(postCCSMsgs, channelIDMsgBytes)
David Benjamind30a9902014-08-24 01:44:23 -04001471 }
1472
Adam Langley95c29f32014-06-20 12:00:00 -07001473 finished := new(finishedMsg)
David Benjaminf3ec83d2014-07-21 22:42:34 -04001474 if c.config.Bugs.EarlyChangeCipherSpec == 2 {
1475 finished.verifyData = hs.finishedHash.clientSum(nil)
1476 } else {
1477 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
1478 }
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001479 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001480 if c.config.Bugs.BadFinished {
1481 finished.verifyData[0]++
1482 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001483 c.clientVerify = append(c.clientVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001484 hs.finishedBytes = finished.marshal()
1485 hs.writeHash(hs.finishedBytes, seqno)
David Benjamin0b8d5da2016-07-15 00:39:56 -04001486 postCCSMsgs = append(postCCSMsgs, hs.finishedBytes)
David Benjamin86271ee2014-07-21 16:14:03 -04001487
1488 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001489 c.writeRecord(recordTypeHandshake, postCCSMsgs[0][:5])
1490 postCCSMsgs[0] = postCCSMsgs[0][5:]
David Benjamin61672812016-07-14 23:10:43 -04001491 } else if c.config.Bugs.SendUnencryptedFinished {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001492 c.writeRecord(recordTypeHandshake, postCCSMsgs[0])
1493 postCCSMsgs = postCCSMsgs[1:]
David Benjamin86271ee2014-07-21 16:14:03 -04001494 }
David Benjamin582ba042016-07-07 12:33:25 -07001495 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001496
1497 if !c.config.Bugs.SkipChangeCipherSpec &&
1498 c.config.Bugs.EarlyChangeCipherSpec == 0 {
David Benjamin8411b242015-11-26 12:07:28 -05001499 ccs := []byte{1}
1500 if c.config.Bugs.BadChangeCipherSpec != nil {
1501 ccs = c.config.Bugs.BadChangeCipherSpec
1502 }
1503 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamin86271ee2014-07-21 16:14:03 -04001504 }
1505
David Benjamin4189bd92015-01-25 23:52:39 -05001506 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1507 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1508 }
David Benjamindc3da932015-03-12 15:09:02 -04001509 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1510 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1511 return errors.New("tls: simulating post-CCS alert")
1512 }
David Benjamin4189bd92015-01-25 23:52:39 -05001513
David Benjamin0b8d5da2016-07-15 00:39:56 -04001514 if !c.config.Bugs.SkipFinished {
1515 for _, msg := range postCCSMsgs {
1516 c.writeRecord(recordTypeHandshake, msg)
1517 }
David Benjamin02edcd02016-07-27 17:40:37 -04001518
1519 if c.config.Bugs.SendExtraFinished {
1520 c.writeRecord(recordTypeHandshake, finished.marshal())
1521 }
1522
David Benjamin582ba042016-07-07 12:33:25 -07001523 c.flushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -05001524 }
Adam Langley95c29f32014-06-20 12:00:00 -07001525 return nil
1526}
1527
Nick Harper60a85cb2016-09-23 16:25:11 -07001528func (hs *clientHandshakeState) writeChannelIDMessage(channelIDHash []byte) ([]byte, error) {
1529 c := hs.c
1530 channelIDMsg := new(channelIDMsg)
1531 if c.config.ChannelID.Curve != elliptic.P256() {
1532 return nil, fmt.Errorf("tls: Channel ID is not on P-256.")
1533 }
1534 r, s, err := ecdsa.Sign(c.config.rand(), c.config.ChannelID, channelIDHash)
1535 if err != nil {
1536 return nil, err
1537 }
1538 channelID := make([]byte, 128)
1539 writeIntPadded(channelID[0:32], c.config.ChannelID.X)
1540 writeIntPadded(channelID[32:64], c.config.ChannelID.Y)
1541 writeIntPadded(channelID[64:96], r)
1542 writeIntPadded(channelID[96:128], s)
1543 if c.config.Bugs.InvalidChannelIDSignature {
1544 channelID[64] ^= 1
1545 }
1546 channelIDMsg.channelID = channelID
1547
1548 c.channelID = &c.config.ChannelID.PublicKey
1549
1550 return channelIDMsg.marshal(), nil
1551}
1552
David Benjamin83c0bc92014-08-04 01:23:53 -04001553func (hs *clientHandshakeState) writeClientHash(msg []byte) {
1554 // writeClientHash is called before writeRecord.
1555 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1556}
1557
1558func (hs *clientHandshakeState) writeServerHash(msg []byte) {
1559 // writeServerHash is called after readHandshake.
1560 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1561}
1562
1563func (hs *clientHandshakeState) writeHash(msg []byte, seqno uint16) {
1564 if hs.c.isDTLS {
1565 // This is somewhat hacky. DTLS hashes a slightly different format.
1566 // First, the TLS header.
1567 hs.finishedHash.Write(msg[:4])
1568 // Then the sequence number and reassembled fragment offset (always 0).
1569 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1570 // Then the reassembled fragment (always equal to the message length).
1571 hs.finishedHash.Write(msg[1:4])
1572 // And then the message body.
1573 hs.finishedHash.Write(msg[4:])
1574 } else {
1575 hs.finishedHash.Write(msg)
1576 }
1577}
1578
David Benjamina6f82632016-07-01 18:44:02 -04001579// selectClientCertificate selects a certificate for use with the given
1580// certificate, or none if none match. It may return a particular certificate or
1581// nil on success, or an error on internal error.
1582func selectClientCertificate(c *Conn, certReq *certificateRequestMsg) (*Certificate, error) {
1583 // RFC 4346 on the certificateAuthorities field:
1584 // A list of the distinguished names of acceptable certificate
1585 // authorities. These distinguished names may specify a desired
1586 // distinguished name for a root CA or for a subordinate CA; thus, this
1587 // message can be used to describe both known roots and a desired
1588 // authorization space. If the certificate_authorities list is empty
1589 // then the client MAY send any certificate of the appropriate
1590 // ClientCertificateType, unless there is some external arrangement to
1591 // the contrary.
1592
1593 var rsaAvail, ecdsaAvail bool
Nick Harperb41d2e42016-07-01 17:50:32 -04001594 if !certReq.hasRequestContext {
1595 for _, certType := range certReq.certificateTypes {
1596 switch certType {
1597 case CertTypeRSASign:
1598 rsaAvail = true
1599 case CertTypeECDSASign:
1600 ecdsaAvail = true
1601 }
David Benjamina6f82632016-07-01 18:44:02 -04001602 }
1603 }
1604
1605 // We need to search our list of client certs for one
1606 // where SignatureAlgorithm is RSA and the Issuer is in
1607 // certReq.certificateAuthorities
1608findCert:
1609 for i, chain := range c.config.Certificates {
Nick Harperb41d2e42016-07-01 17:50:32 -04001610 if !certReq.hasRequestContext && !rsaAvail && !ecdsaAvail {
David Benjamina6f82632016-07-01 18:44:02 -04001611 continue
1612 }
1613
1614 // Ensure the private key supports one of the advertised
1615 // signature algorithms.
1616 if certReq.hasSignatureAlgorithm {
David Benjamin0a8deb22016-07-09 21:02:01 -07001617 if _, err := selectSignatureAlgorithm(c.vers, chain.PrivateKey, c.config, certReq.signatureAlgorithms); err != nil {
David Benjamina6f82632016-07-01 18:44:02 -04001618 continue
1619 }
1620 }
1621
1622 for j, cert := range chain.Certificate {
1623 x509Cert := chain.Leaf
1624 // parse the certificate if this isn't the leaf
1625 // node, or if chain.Leaf was nil
1626 if j != 0 || x509Cert == nil {
1627 var err error
1628 if x509Cert, err = x509.ParseCertificate(cert); err != nil {
1629 c.sendAlert(alertInternalError)
1630 return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
1631 }
1632 }
1633
Nick Harperb41d2e42016-07-01 17:50:32 -04001634 if !certReq.hasRequestContext {
1635 switch {
1636 case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
1637 case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
1638 default:
1639 continue findCert
1640 }
David Benjamina6f82632016-07-01 18:44:02 -04001641 }
1642
1643 if len(certReq.certificateAuthorities) == 0 {
1644 // They gave us an empty list, so just take the
1645 // first certificate of valid type from
1646 // c.config.Certificates.
1647 return &chain, nil
1648 }
1649
1650 for _, ca := range certReq.certificateAuthorities {
1651 if bytes.Equal(x509Cert.RawIssuer, ca) {
1652 return &chain, nil
1653 }
1654 }
1655 }
1656 }
1657
1658 return nil, nil
1659}
1660
Adam Langley95c29f32014-06-20 12:00:00 -07001661// clientSessionCacheKey returns a key used to cache sessionTickets that could
1662// be used to resume previously negotiated TLS sessions with a server.
1663func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
1664 if len(config.ServerName) > 0 {
1665 return config.ServerName
1666 }
1667 return serverAddr.String()
1668}
1669
David Benjaminfa055a22014-09-15 16:51:51 -04001670// mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
1671// given list of possible protocols and a list of the preference order. The
1672// first list must not be empty. It returns the resulting protocol and flag
Adam Langley95c29f32014-06-20 12:00:00 -07001673// indicating if the fallback case was reached.
David Benjaminfa055a22014-09-15 16:51:51 -04001674func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
1675 for _, s := range preferenceProtos {
1676 for _, c := range protos {
Adam Langley95c29f32014-06-20 12:00:00 -07001677 if s == c {
1678 return s, false
1679 }
1680 }
1681 }
1682
David Benjaminfa055a22014-09-15 16:51:51 -04001683 return protos[0], true
Adam Langley95c29f32014-06-20 12:00:00 -07001684}
David Benjamind30a9902014-08-24 01:44:23 -04001685
1686// writeIntPadded writes x into b, padded up with leading zeros as
1687// needed.
1688func writeIntPadded(b []byte, x *big.Int) {
1689 for i := range b {
1690 b[i] = 0
1691 }
1692 xb := x.Bytes()
1693 copy(b[len(b)-len(xb):], xb)
1694}
Steven Valdeza833c352016-11-01 13:39:36 -04001695
1696func generatePSKBinders(hello *clientHelloMsg, pskCipherSuite *cipherSuite, psk, transcript []byte, config *Config) {
1697 if config.Bugs.SendNoPSKBinder {
1698 return
1699 }
1700
1701 binderLen := pskCipherSuite.hash().Size()
1702 if config.Bugs.SendShortPSKBinder {
1703 binderLen--
1704 }
1705
David Benjaminaedf3032016-12-01 16:47:56 -05001706 numBinders := 1
1707 if config.Bugs.SendExtraPSKBinder {
1708 numBinders++
1709 }
1710
Steven Valdeza833c352016-11-01 13:39:36 -04001711 // Fill hello.pskBinders with appropriate length arrays of zeros so the
1712 // length prefixes are correct when computing the binder over the truncated
1713 // ClientHello message.
David Benjaminaedf3032016-12-01 16:47:56 -05001714 hello.pskBinders = make([][]byte, numBinders)
1715 for i := range hello.pskBinders {
Steven Valdeza833c352016-11-01 13:39:36 -04001716 hello.pskBinders[i] = make([]byte, binderLen)
1717 }
1718
1719 helloBytes := hello.marshal()
1720 binderSize := len(hello.pskBinders)*(binderLen+1) + 2
1721 truncatedHello := helloBytes[:len(helloBytes)-binderSize]
1722 binder := computePSKBinder(psk, resumptionPSKBinderLabel, pskCipherSuite, transcript, truncatedHello)
1723 if config.Bugs.SendShortPSKBinder {
1724 binder = binder[:binderLen]
1725 }
1726 if config.Bugs.SendInvalidPSKBinder {
1727 binder[0] ^= 1
1728 }
1729
1730 for i := range hello.pskBinders {
1731 hello.pskBinders[i] = binder
1732 }
1733
1734 hello.raw = nil
1735}