blob: 9691ae623db063af737eaf6a452f39949a6c4a6f [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
Adam Langley2ae77d22014-10-28 17:29:33 -0700108 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
109 if c.config.Bugs.BadRenegotiationInfo {
110 hello.secureRenegotiation = append(hello.secureRenegotiation, c.clientVerify...)
111 hello.secureRenegotiation[0] ^= 0x80
112 } else {
113 hello.secureRenegotiation = c.clientVerify
114 }
115 }
116
David Benjamin3e052de2015-11-25 20:10:31 -0500117 if c.noRenegotiationInfo() {
David Benjaminca6554b2014-11-08 12:31:52 -0500118 hello.secureRenegotiation = nil
119 }
120
Nick Harperb41d2e42016-07-01 17:50:32 -0400121 var keyShares map[CurveID]ecdhCurve
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400122 if maxVersion >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -0400123 keyShares = make(map[CurveID]ecdhCurve)
Nick Harperdcfbc672016-07-16 17:47:31 +0200124 hello.hasKeyShares = true
David Benjamin7e1f9842016-09-20 19:24:40 -0400125 hello.trailingKeyShareData = c.config.Bugs.TrailingKeyShareData
Nick Harperdcfbc672016-07-16 17:47:31 +0200126 curvesToSend := c.config.defaultCurves()
Nick Harperb41d2e42016-07-01 17:50:32 -0400127 for _, curveID := range hello.supportedCurves {
Nick Harperdcfbc672016-07-16 17:47:31 +0200128 if !curvesToSend[curveID] {
129 continue
130 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400131 curve, ok := curveForCurveID(curveID)
132 if !ok {
133 continue
134 }
135 publicKey, err := curve.offer(c.config.rand())
136 if err != nil {
137 return err
138 }
Steven Valdez0ee2e112016-07-15 06:51:15 -0400139
140 if c.config.Bugs.SendCurve != 0 {
141 curveID = c.config.Bugs.SendCurve
142 }
143 if c.config.Bugs.InvalidECDHPoint {
144 publicKey[0] ^= 0xff
145 }
146
Nick Harperb41d2e42016-07-01 17:50:32 -0400147 hello.keyShares = append(hello.keyShares, keyShareEntry{
148 group: curveID,
149 keyExchange: publicKey,
150 })
151 keyShares[curveID] = curve
Steven Valdez143e8b32016-07-11 13:19:03 -0400152
153 if c.config.Bugs.DuplicateKeyShares {
154 hello.keyShares = append(hello.keyShares, hello.keyShares[len(hello.keyShares)-1])
155 }
156 }
157
158 if c.config.Bugs.MissingKeyShare {
Steven Valdez5440fe02016-07-18 12:40:30 -0400159 hello.hasKeyShares = false
Nick Harperb41d2e42016-07-01 17:50:32 -0400160 }
161 }
162
Adam Langley95c29f32014-06-20 12:00:00 -0700163 possibleCipherSuites := c.config.cipherSuites()
164 hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
165
166NextCipherSuite:
167 for _, suiteId := range possibleCipherSuites {
168 for _, suite := range cipherSuites {
169 if suite.id != suiteId {
170 continue
171 }
David Benjamin5ecb88b2016-10-04 17:51:35 -0400172 // Don't advertise TLS 1.2-only cipher suites unless
173 // we're attempting TLS 1.2.
174 if maxVersion < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
175 continue
176 }
177 // Don't advertise non-DTLS cipher suites in DTLS.
178 if c.isDTLS && suite.flags&suiteNoDTLS != 0 {
179 continue
David Benjamin83c0bc92014-08-04 01:23:53 -0400180 }
Adam Langley95c29f32014-06-20 12:00:00 -0700181 hello.cipherSuites = append(hello.cipherSuites, suiteId)
182 continue NextCipherSuite
183 }
184 }
185
David Benjamin5ecb88b2016-10-04 17:51:35 -0400186 if c.config.Bugs.AdvertiseAllConfiguredCiphers {
187 hello.cipherSuites = possibleCipherSuites
188 }
189
Adam Langley5021b222015-06-12 18:27:58 -0700190 if c.config.Bugs.SendRenegotiationSCSV {
191 hello.cipherSuites = append(hello.cipherSuites, renegotiationSCSV)
192 }
193
David Benjaminbef270a2014-08-02 04:22:02 -0400194 if c.config.Bugs.SendFallbackSCSV {
195 hello.cipherSuites = append(hello.cipherSuites, fallbackSCSV)
196 }
197
Adam Langley95c29f32014-06-20 12:00:00 -0700198 _, err := io.ReadFull(c.config.rand(), hello.random)
199 if err != nil {
200 c.sendAlert(alertInternalError)
201 return errors.New("tls: short read from Rand: " + err.Error())
202 }
203
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400204 if maxVersion >= VersionTLS12 && !c.config.Bugs.NoSignatureAlgorithms {
David Benjamin7a41d372016-07-09 11:21:54 -0700205 hello.signatureAlgorithms = c.config.verifySignatureAlgorithms()
Adam Langley95c29f32014-06-20 12:00:00 -0700206 }
207
208 var session *ClientSessionState
209 var cacheKey string
210 sessionCache := c.config.ClientSessionCache
Adam Langley95c29f32014-06-20 12:00:00 -0700211
212 if sessionCache != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500213 hello.ticketSupported = !c.config.SessionTicketsDisabled
Adam Langley95c29f32014-06-20 12:00:00 -0700214
215 // Try to resume a previously negotiated TLS session, if
216 // available.
217 cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
Nick Harper0b3625b2016-07-25 16:16:28 -0700218 // TODO(nharper): Support storing more than one session
219 // ticket for TLS 1.3.
Adam Langley95c29f32014-06-20 12:00:00 -0700220 candidateSession, ok := sessionCache.Get(cacheKey)
221 if ok {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500222 ticketOk := !c.config.SessionTicketsDisabled || candidateSession.sessionTicket == nil
223
Adam Langley95c29f32014-06-20 12:00:00 -0700224 // Check that the ciphersuite/version used for the
225 // previous session are still valid.
226 cipherSuiteOk := false
David Benjamin2b02f4b2016-11-16 16:11:47 +0900227 if candidateSession.vers <= VersionTLS12 {
228 for _, id := range hello.cipherSuites {
229 if id == candidateSession.cipherSuite {
230 cipherSuiteOk = true
231 break
232 }
Adam Langley95c29f32014-06-20 12:00:00 -0700233 }
David Benjamin2b02f4b2016-11-16 16:11:47 +0900234 } else {
235 // TLS 1.3 allows the cipher to change on
236 // resumption.
237 cipherSuiteOk = true
Adam Langley95c29f32014-06-20 12:00:00 -0700238 }
239
Steven Valdezfdd10992016-09-15 16:27:05 -0400240 versOk := candidateSession.vers >= minVersion &&
241 candidateSession.vers <= maxVersion
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500242 if ticketOk && versOk && cipherSuiteOk {
Adam Langley95c29f32014-06-20 12:00:00 -0700243 session = candidateSession
244 }
245 }
246 }
247
Steven Valdeza833c352016-11-01 13:39:36 -0400248 var pskCipherSuite *cipherSuite
Nick Harper0b3625b2016-07-25 16:16:28 -0700249 if session != nil && c.config.time().Before(session.ticketExpiration) {
David Benjamind5a4ecb2016-07-18 01:17:13 +0200250 ticket := session.sessionTicket
David Benjamin4199b0d2016-11-01 13:58:25 -0400251 if c.config.Bugs.FilterTicket != nil && len(ticket) > 0 {
252 // Copy the ticket so FilterTicket may act in-place.
David Benjamind5a4ecb2016-07-18 01:17:13 +0200253 ticket = make([]byte, len(session.sessionTicket))
254 copy(ticket, session.sessionTicket)
David Benjamin4199b0d2016-11-01 13:58:25 -0400255
256 ticket, err = c.config.Bugs.FilterTicket(ticket)
257 if err != nil {
258 return err
Adam Langley38311732014-10-16 19:04:35 -0700259 }
David Benjamind5a4ecb2016-07-18 01:17:13 +0200260 }
261
David Benjamin405da482016-08-08 17:25:07 -0400262 if session.vers >= VersionTLS13 || c.config.Bugs.SendBothTickets {
Steven Valdeza833c352016-11-01 13:39:36 -0400263 pskCipherSuite = cipherSuiteFromID(session.cipherSuite)
264 if pskCipherSuite == nil {
265 return errors.New("tls: client session cache has invalid cipher suite")
266 }
Nick Harper0b3625b2016-07-25 16:16:28 -0700267 // TODO(nharper): Support sending more
268 // than one PSK identity.
Steven Valdeza833c352016-11-01 13:39:36 -0400269 ticketAge := uint32(c.config.time().Sub(session.ticketCreationTime) / time.Millisecond)
Steven Valdez5b986082016-09-01 12:29:49 -0400270 psk := pskIdentity{
Steven Valdeza833c352016-11-01 13:39:36 -0400271 ticket: ticket,
272 obfuscatedTicketAge: session.ticketAgeAdd + ticketAge,
Nick Harper0b3625b2016-07-25 16:16:28 -0700273 }
Steven Valdez5b986082016-09-01 12:29:49 -0400274 hello.pskIdentities = []pskIdentity{psk}
Steven Valdezaf3b8a92016-11-01 12:49:22 -0400275
276 if c.config.Bugs.ExtraPSKIdentity {
277 hello.pskIdentities = append(hello.pskIdentities, psk)
278 }
David Benjamin405da482016-08-08 17:25:07 -0400279 }
280
281 if session.vers < VersionTLS13 || c.config.Bugs.SendBothTickets {
282 if ticket != nil {
283 hello.sessionTicket = ticket
284 // A random session ID is used to detect when the
285 // server accepted the ticket and is resuming a session
286 // (see RFC 5077).
287 sessionIdLen := 16
288 if c.config.Bugs.OversizedSessionId {
289 sessionIdLen = 33
290 }
291 hello.sessionId = make([]byte, sessionIdLen)
292 if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
293 c.sendAlert(alertInternalError)
294 return errors.New("tls: short read from Rand: " + err.Error())
295 }
296 } else {
297 hello.sessionId = session.sessionId
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500298 }
Adam Langley95c29f32014-06-20 12:00:00 -0700299 }
300 }
301
Steven Valdezfdd10992016-09-15 16:27:05 -0400302 if maxVersion == VersionTLS13 && !c.config.Bugs.OmitSupportedVersions {
303 if hello.vers >= VersionTLS13 {
304 hello.vers = VersionTLS12
305 }
306 for version := maxVersion; version >= minVersion; version-- {
307 hello.supportedVersions = append(hello.supportedVersions, versionToWire(version, c.isDTLS))
308 }
309 }
310
311 if len(c.config.Bugs.SendSupportedVersions) > 0 {
312 hello.supportedVersions = c.config.Bugs.SendSupportedVersions
313 }
314
David Benjamineed24012016-08-13 19:26:00 -0400315 if c.config.Bugs.SendClientVersion != 0 {
316 hello.vers = c.config.Bugs.SendClientVersion
317 }
318
David Benjamin75f99142016-11-12 12:36:06 +0900319 if c.config.Bugs.SendCipherSuites != nil {
320 hello.cipherSuites = c.config.Bugs.SendCipherSuites
321 }
322
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500323 if c.config.Bugs.SendEarlyDataLength > 0 && !c.config.Bugs.OmitEarlyDataExtension {
324 hello.hasEarlyData = true
325 }
326
David Benjamind86c7672014-08-02 04:07:12 -0400327 var helloBytes []byte
328 if c.config.Bugs.SendV2ClientHello {
David Benjamin94d701b2014-11-30 13:54:41 -0500329 // Test that the peer left-pads random.
330 hello.random[0] = 0
David Benjamind86c7672014-08-02 04:07:12 -0400331 v2Hello := &v2ClientHelloMsg{
332 vers: hello.vers,
333 cipherSuites: hello.cipherSuites,
334 // No session resumption for V2ClientHello.
335 sessionId: nil,
David Benjamin94d701b2014-11-30 13:54:41 -0500336 challenge: hello.random[1:],
David Benjamind86c7672014-08-02 04:07:12 -0400337 }
338 helloBytes = v2Hello.marshal()
339 c.writeV2Record(helloBytes)
340 } else {
Steven Valdeza833c352016-11-01 13:39:36 -0400341 if len(hello.pskIdentities) > 0 {
342 generatePSKBinders(hello, pskCipherSuite, session.masterSecret, []byte{}, c.config)
343 }
David Benjamind86c7672014-08-02 04:07:12 -0400344 helloBytes = hello.marshal()
Steven Valdeza833c352016-11-01 13:39:36 -0400345
David Benjamin7964b182016-07-14 23:36:30 -0400346 if c.config.Bugs.PartialClientFinishedWithClientHello {
347 // Include one byte of Finished. We can compute it
348 // without completing the handshake. This assumes we
349 // negotiate TLS 1.3 with no HelloRetryRequest or
350 // CertificateRequest.
351 toWrite := make([]byte, 0, len(helloBytes)+1)
352 toWrite = append(toWrite, helloBytes...)
353 toWrite = append(toWrite, typeFinished)
354 c.writeRecord(recordTypeHandshake, toWrite)
355 } else {
356 c.writeRecord(recordTypeHandshake, helloBytes)
357 }
David Benjamind86c7672014-08-02 04:07:12 -0400358 }
David Benjamin582ba042016-07-07 12:33:25 -0700359 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700360
David Benjamin83f90402015-01-27 01:09:43 -0500361 if err := c.simulatePacketLoss(nil); err != nil {
362 return err
363 }
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500364 if c.config.Bugs.SendEarlyAlert {
365 c.sendAlert(alertHandshakeFailure)
366 }
367 if c.config.Bugs.SendEarlyDataLength > 0 {
368 c.sendFakeEarlyData(c.config.Bugs.SendEarlyDataLength)
369 }
Adam Langley95c29f32014-06-20 12:00:00 -0700370 msg, err := c.readHandshake()
371 if err != nil {
372 return err
373 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400374
375 if c.isDTLS {
376 helloVerifyRequest, ok := msg.(*helloVerifyRequestMsg)
377 if ok {
David Benjaminda4789e2016-10-31 19:23:34 -0400378 if helloVerifyRequest.vers != versionToWire(VersionTLS10, c.isDTLS) {
David Benjamin8bc38f52014-08-16 12:07:27 -0400379 // Per RFC 6347, the version field in
380 // HelloVerifyRequest SHOULD be always DTLS
381 // 1.0. Enforce this for testing purposes.
382 return errors.New("dtls: bad HelloVerifyRequest version")
383 }
384
David Benjamin83c0bc92014-08-04 01:23:53 -0400385 hello.raw = nil
386 hello.cookie = helloVerifyRequest.cookie
387 helloBytes = hello.marshal()
388 c.writeRecord(recordTypeHandshake, helloBytes)
David Benjamin582ba042016-07-07 12:33:25 -0700389 c.flushHandshake()
David Benjamin83c0bc92014-08-04 01:23:53 -0400390
David Benjamin83f90402015-01-27 01:09:43 -0500391 if err := c.simulatePacketLoss(nil); err != nil {
392 return err
393 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400394 msg, err = c.readHandshake()
395 if err != nil {
396 return err
397 }
398 }
399 }
400
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400401 var serverWireVersion uint16
Nick Harperdcfbc672016-07-16 17:47:31 +0200402 switch m := msg.(type) {
403 case *helloRetryRequestMsg:
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400404 serverWireVersion = m.vers
Nick Harperdcfbc672016-07-16 17:47:31 +0200405 case *serverHelloMsg:
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400406 serverWireVersion = m.vers
Nick Harperdcfbc672016-07-16 17:47:31 +0200407 default:
408 c.sendAlert(alertUnexpectedMessage)
409 return fmt.Errorf("tls: received unexpected message of type %T when waiting for HelloRetryRequest or ServerHello", msg)
410 }
411
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400412 serverVersion, ok := wireToVersion(serverWireVersion, c.isDTLS)
413 if ok {
Steven Valdezfdd10992016-09-15 16:27:05 -0400414 ok = c.config.isSupportedVersion(serverVersion, c.isDTLS)
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400415 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200416 if !ok {
417 c.sendAlert(alertProtocolVersion)
418 return fmt.Errorf("tls: server selected unsupported protocol version %x", c.vers)
419 }
Steven Valdezfdd10992016-09-15 16:27:05 -0400420 c.vers = serverVersion
Nick Harperdcfbc672016-07-16 17:47:31 +0200421 c.haveVers = true
422
423 helloRetryRequest, haveHelloRetryRequest := msg.(*helloRetryRequestMsg)
424 var secondHelloBytes []byte
425 if haveHelloRetryRequest {
David Benjamin3baa6e12016-10-07 21:10:38 -0400426 if len(helloRetryRequest.cookie) > 0 {
427 hello.tls13Cookie = helloRetryRequest.cookie
428 }
429
Steven Valdez5440fe02016-07-18 12:40:30 -0400430 if c.config.Bugs.MisinterpretHelloRetryRequestCurve != 0 {
David Benjamin3baa6e12016-10-07 21:10:38 -0400431 helloRetryRequest.hasSelectedGroup = true
Steven Valdez5440fe02016-07-18 12:40:30 -0400432 helloRetryRequest.selectedGroup = c.config.Bugs.MisinterpretHelloRetryRequestCurve
433 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400434 if helloRetryRequest.hasSelectedGroup {
435 var hrrCurveFound bool
436 group := helloRetryRequest.selectedGroup
437 for _, curveID := range hello.supportedCurves {
438 if group == curveID {
439 hrrCurveFound = true
440 break
441 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200442 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400443 if !hrrCurveFound || keyShares[group] != nil {
444 c.sendAlert(alertHandshakeFailure)
445 return errors.New("tls: received invalid HelloRetryRequest")
446 }
447 curve, ok := curveForCurveID(group)
448 if !ok {
449 return errors.New("tls: Unable to get curve requested in HelloRetryRequest")
450 }
451 publicKey, err := curve.offer(c.config.rand())
452 if err != nil {
453 return err
454 }
455 keyShares[group] = curve
Steven Valdeza833c352016-11-01 13:39:36 -0400456 hello.keyShares = []keyShareEntry{{
David Benjamin3baa6e12016-10-07 21:10:38 -0400457 group: group,
458 keyExchange: publicKey,
Steven Valdeza833c352016-11-01 13:39:36 -0400459 }}
Nick Harperdcfbc672016-07-16 17:47:31 +0200460 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200461
Steven Valdez5440fe02016-07-18 12:40:30 -0400462 if c.config.Bugs.SecondClientHelloMissingKeyShare {
463 hello.hasKeyShares = false
464 }
465
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500466 hello.hasEarlyData = c.config.Bugs.SendEarlyDataOnSecondClientHello
Nick Harperdcfbc672016-07-16 17:47:31 +0200467 hello.raw = nil
468
Steven Valdeza833c352016-11-01 13:39:36 -0400469 if len(hello.pskIdentities) > 0 {
470 generatePSKBinders(hello, pskCipherSuite, session.masterSecret, append(helloBytes, helloRetryRequest.marshal()...), c.config)
471 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200472 secondHelloBytes = hello.marshal()
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500473
474 if c.config.Bugs.InterleaveEarlyData {
475 c.sendFakeEarlyData(4)
476 c.writeRecord(recordTypeHandshake, secondHelloBytes[:16])
477 c.sendFakeEarlyData(4)
478 c.writeRecord(recordTypeHandshake, secondHelloBytes[16:])
479 } else {
480 c.writeRecord(recordTypeHandshake, secondHelloBytes)
481 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200482 c.flushHandshake()
483
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500484 if c.config.Bugs.SendEarlyDataOnSecondClientHello {
485 c.sendFakeEarlyData(4)
486 }
487
Nick Harperdcfbc672016-07-16 17:47:31 +0200488 msg, err = c.readHandshake()
489 if err != nil {
490 return err
491 }
492 }
493
Adam Langley95c29f32014-06-20 12:00:00 -0700494 serverHello, ok := msg.(*serverHelloMsg)
495 if !ok {
496 c.sendAlert(alertUnexpectedMessage)
497 return unexpectedMessageError(serverHello, msg)
498 }
499
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400500 if serverWireVersion != serverHello.vers {
Adam Langley95c29f32014-06-20 12:00:00 -0700501 c.sendAlert(alertProtocolVersion)
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400502 return fmt.Errorf("tls: server sent non-matching version %x vs %x", serverWireVersion, serverHello.vers)
Adam Langley95c29f32014-06-20 12:00:00 -0700503 }
Adam Langley95c29f32014-06-20 12:00:00 -0700504
Nick Harper85f20c22016-07-04 10:11:59 -0700505 // Check for downgrade signals in the server random, per
David Benjamina128a552016-10-13 14:26:33 -0400506 // draft-ietf-tls-tls13-16, section 4.1.3.
Nick Harper85f20c22016-07-04 10:11:59 -0700507 if c.vers <= VersionTLS12 && c.config.maxVersion(c.isDTLS) >= VersionTLS13 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400508 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS13) {
Nick Harper85f20c22016-07-04 10:11:59 -0700509 c.sendAlert(alertProtocolVersion)
510 return errors.New("tls: downgrade from TLS 1.3 detected")
511 }
512 }
513 if c.vers <= VersionTLS11 && c.config.maxVersion(c.isDTLS) >= VersionTLS12 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400514 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS12) {
Nick Harper85f20c22016-07-04 10:11:59 -0700515 c.sendAlert(alertProtocolVersion)
516 return errors.New("tls: downgrade from TLS 1.2 detected")
517 }
518 }
519
Nick Harper0b3625b2016-07-25 16:16:28 -0700520 suite := mutualCipherSuite(hello.cipherSuites, serverHello.cipherSuite)
Adam Langley95c29f32014-06-20 12:00:00 -0700521 if suite == nil {
522 c.sendAlert(alertHandshakeFailure)
523 return fmt.Errorf("tls: server selected an unsupported cipher suite")
524 }
525
David Benjamin3baa6e12016-10-07 21:10:38 -0400526 if haveHelloRetryRequest && helloRetryRequest.hasSelectedGroup && helloRetryRequest.selectedGroup != serverHello.keyShare.group {
Nick Harperdcfbc672016-07-16 17:47:31 +0200527 c.sendAlert(alertHandshakeFailure)
528 return errors.New("tls: ServerHello parameters did not match HelloRetryRequest")
529 }
530
Adam Langley95c29f32014-06-20 12:00:00 -0700531 hs := &clientHandshakeState{
532 c: c,
533 serverHello: serverHello,
534 hello: hello,
535 suite: suite,
536 finishedHash: newFinishedHash(c.vers, suite),
Nick Harperb41d2e42016-07-01 17:50:32 -0400537 keyShares: keyShares,
Adam Langley95c29f32014-06-20 12:00:00 -0700538 session: session,
539 }
540
David Benjamin83c0bc92014-08-04 01:23:53 -0400541 hs.writeHash(helloBytes, hs.c.sendHandshakeSeq-1)
Nick Harperdcfbc672016-07-16 17:47:31 +0200542 if haveHelloRetryRequest {
543 hs.writeServerHash(helloRetryRequest.marshal())
544 hs.writeClientHash(secondHelloBytes)
545 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400546 hs.writeServerHash(hs.serverHello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700547
David Benjamin8d315d72016-07-18 01:03:18 +0200548 if c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -0400549 if err := hs.doTLS13Handshake(); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700550 return err
551 }
552 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400553 if c.config.Bugs.EarlyChangeCipherSpec > 0 {
554 hs.establishKeys()
555 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
556 }
557
558 if hs.serverHello.compressionMethod != compressionNone {
559 c.sendAlert(alertUnexpectedMessage)
560 return errors.New("tls: server selected unsupported compression format")
561 }
562
563 err = hs.processServerExtensions(&serverHello.extensions)
564 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700565 return err
566 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400567
568 isResume, err := hs.processServerHello()
569 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700570 return err
571 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400572
573 if isResume {
574 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
575 if err := hs.establishKeys(); err != nil {
576 return err
577 }
578 }
579 if err := hs.readSessionTicket(); err != nil {
580 return err
581 }
582 if err := hs.readFinished(c.firstFinished[:]); err != nil {
583 return err
584 }
585 if err := hs.sendFinished(nil, isResume); err != nil {
586 return err
587 }
588 } else {
589 if err := hs.doFullHandshake(); err != nil {
590 return err
591 }
592 if err := hs.establishKeys(); err != nil {
593 return err
594 }
595 if err := hs.sendFinished(c.firstFinished[:], isResume); err != nil {
596 return err
597 }
598 // Most retransmits are triggered by a timeout, but the final
599 // leg of the handshake is retransmited upon re-receiving a
600 // Finished.
601 if err := c.simulatePacketLoss(func() {
David Benjamin02edcd02016-07-27 17:40:37 -0400602 c.sendHandshakeSeq--
Nick Harperb41d2e42016-07-01 17:50:32 -0400603 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
604 c.flushHandshake()
605 }); err != nil {
606 return err
607 }
608 if err := hs.readSessionTicket(); err != nil {
609 return err
610 }
611 if err := hs.readFinished(nil); err != nil {
612 return err
613 }
Adam Langley95c29f32014-06-20 12:00:00 -0700614 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400615
616 if sessionCache != nil && hs.session != nil && session != hs.session {
617 if c.config.Bugs.RequireSessionTickets && len(hs.session.sessionTicket) == 0 {
618 return errors.New("tls: new session used session IDs instead of tickets")
619 }
620 sessionCache.Put(cacheKey, hs.session)
David Benjamin83f90402015-01-27 01:09:43 -0500621 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400622
623 c.didResume = isResume
David Benjamin97a0a082016-07-13 17:57:35 -0400624 c.exporterSecret = hs.masterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700625 }
626
Adam Langley95c29f32014-06-20 12:00:00 -0700627 c.handshakeComplete = true
David Benjaminc565ebb2015-04-03 04:06:36 -0400628 c.cipherSuite = suite
629 copy(c.clientRandom[:], hs.hello.random)
630 copy(c.serverRandom[:], hs.serverHello.random)
Paul Lietar4fac72e2015-09-09 13:44:55 +0100631
Adam Langley95c29f32014-06-20 12:00:00 -0700632 return nil
633}
634
Nick Harperb41d2e42016-07-01 17:50:32 -0400635func (hs *clientHandshakeState) doTLS13Handshake() error {
636 c := hs.c
637
638 // Once the PRF hash is known, TLS 1.3 does not require a handshake
639 // buffer.
640 hs.finishedHash.discardHandshakeBuffer()
641
642 zeroSecret := hs.finishedHash.zeroSecret()
643
644 // Resolve PSK and compute the early secret.
645 //
646 // TODO(davidben): This will need to be handled slightly earlier once
647 // 0-RTT is implemented.
Steven Valdez803c77a2016-09-06 14:13:43 -0400648 if hs.serverHello.hasPSKIdentity {
Nick Harper0b3625b2016-07-25 16:16:28 -0700649 // We send at most one PSK identity.
650 if hs.session == nil || hs.serverHello.pskIdentity != 0 {
651 c.sendAlert(alertUnknownPSKIdentity)
652 return errors.New("tls: server sent unknown PSK identity")
653 }
David Benjamin2b02f4b2016-11-16 16:11:47 +0900654 sessionCipher := cipherSuiteFromID(hs.session.cipherSuite)
655 if sessionCipher == nil || sessionCipher.hash() != hs.suite.hash() {
Nick Harper0b3625b2016-07-25 16:16:28 -0700656 c.sendAlert(alertHandshakeFailure)
David Benjamin2b02f4b2016-11-16 16:11:47 +0900657 return errors.New("tls: server resumed an invalid session for the cipher suite")
Nick Harper0b3625b2016-07-25 16:16:28 -0700658 }
David Benjamin48891ad2016-12-04 00:02:43 -0500659 hs.finishedHash.addEntropy(hs.session.masterSecret)
Nick Harper0b3625b2016-07-25 16:16:28 -0700660 c.didResume = true
Nick Harperb41d2e42016-07-01 17:50:32 -0400661 } else {
David Benjamin48891ad2016-12-04 00:02:43 -0500662 hs.finishedHash.addEntropy(zeroSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400663 }
664
Steven Valdeza833c352016-11-01 13:39:36 -0400665 if !hs.serverHello.hasKeyShare {
666 c.sendAlert(alertUnsupportedExtension)
667 return errors.New("tls: server omitted KeyShare on resumption.")
668 }
669
Nick Harperb41d2e42016-07-01 17:50:32 -0400670 // Resolve ECDHE and compute the handshake secret.
Steven Valdez803c77a2016-09-06 14:13:43 -0400671 if !c.config.Bugs.MissingKeyShare && !c.config.Bugs.SecondClientHelloMissingKeyShare {
Nick Harperb41d2e42016-07-01 17:50:32 -0400672 curve, ok := hs.keyShares[hs.serverHello.keyShare.group]
673 if !ok {
674 c.sendAlert(alertHandshakeFailure)
675 return errors.New("tls: server selected an unsupported group")
676 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400677 c.curveID = hs.serverHello.keyShare.group
Nick Harperb41d2e42016-07-01 17:50:32 -0400678
David Benjamin48891ad2016-12-04 00:02:43 -0500679 ecdheSecret, err := curve.finish(hs.serverHello.keyShare.keyExchange)
Nick Harperb41d2e42016-07-01 17:50:32 -0400680 if err != nil {
681 return err
682 }
David Benjamin48891ad2016-12-04 00:02:43 -0500683 hs.finishedHash.addEntropy(ecdheSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400684 } else {
David Benjamin48891ad2016-12-04 00:02:43 -0500685 hs.finishedHash.addEntropy(zeroSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400686 }
687
David Benjamin6f600d62016-12-21 16:06:54 -0500688 if hs.serverHello.shortHeader && !hs.hello.shortHeaderSupported {
689 return errors.New("tls: server sent unsolicited short header extension")
690 }
691
692 if hs.serverHello.shortHeader && hs.hello.hasEarlyData {
693 return errors.New("tls: server sent short header extension in response to early data")
694 }
695
696 if hs.serverHello.shortHeader {
697 c.setShortHeader()
698 }
699
Nick Harperb41d2e42016-07-01 17:50:32 -0400700 // Switch to handshake traffic keys.
David Benjamin48891ad2016-12-04 00:02:43 -0500701 clientHandshakeTrafficSecret := hs.finishedHash.deriveSecret(clientHandshakeTrafficLabel)
Steven Valdeza833c352016-11-01 13:39:36 -0400702 c.out.useTrafficSecret(c.vers, hs.suite, clientHandshakeTrafficSecret, clientWrite)
David Benjamin48891ad2016-12-04 00:02:43 -0500703 serverHandshakeTrafficSecret := hs.finishedHash.deriveSecret(serverHandshakeTrafficLabel)
Steven Valdeza833c352016-11-01 13:39:36 -0400704 c.in.useTrafficSecret(c.vers, hs.suite, serverHandshakeTrafficSecret, serverWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -0400705
706 msg, err := c.readHandshake()
707 if err != nil {
708 return err
709 }
710
711 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
712 if !ok {
713 c.sendAlert(alertUnexpectedMessage)
714 return unexpectedMessageError(encryptedExtensions, msg)
715 }
716 hs.writeServerHash(encryptedExtensions.marshal())
717
718 err = hs.processServerExtensions(&encryptedExtensions.extensions)
719 if err != nil {
720 return err
721 }
722
723 var chainToSend *Certificate
David Benjamin8d343b42016-07-09 14:26:01 -0700724 var certReq *certificateRequestMsg
Steven Valdeza833c352016-11-01 13:39:36 -0400725 if c.didResume {
Nick Harper0b3625b2016-07-25 16:16:28 -0700726 // Copy over authentication from the session.
727 c.peerCertificates = hs.session.serverCertificates
728 c.sctList = hs.session.sctList
729 c.ocspResponse = hs.session.ocspResponse
David Benjamin44b33bc2016-07-01 22:40:23 -0400730 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400731 msg, err := c.readHandshake()
732 if err != nil {
733 return err
734 }
735
David Benjamin8d343b42016-07-09 14:26:01 -0700736 var ok bool
737 certReq, ok = msg.(*certificateRequestMsg)
Nick Harperb41d2e42016-07-01 17:50:32 -0400738 if ok {
David Benjamin8a8349b2016-08-18 02:32:23 -0400739 if len(certReq.requestContext) != 0 {
740 return errors.New("tls: non-empty certificate request context sent in handshake")
741 }
742
David Benjaminb62d2872016-07-18 14:55:02 +0200743 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
744 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
745 }
746
Nick Harperb41d2e42016-07-01 17:50:32 -0400747 hs.writeServerHash(certReq.marshal())
Nick Harperb41d2e42016-07-01 17:50:32 -0400748
749 chainToSend, err = selectClientCertificate(c, certReq)
750 if err != nil {
751 return err
752 }
753
754 msg, err = c.readHandshake()
755 if err != nil {
756 return err
757 }
758 }
759
760 certMsg, ok := msg.(*certificateMsg)
761 if !ok {
762 c.sendAlert(alertUnexpectedMessage)
763 return unexpectedMessageError(certMsg, msg)
764 }
765 hs.writeServerHash(certMsg.marshal())
766
David Benjamin53210cb2016-11-16 09:01:48 +0900767 // Check for unsolicited extensions.
768 for i, cert := range certMsg.certificates {
769 if c.config.Bugs.NoOCSPStapling && cert.ocspResponse != nil {
770 c.sendAlert(alertUnsupportedExtension)
771 return errors.New("tls: unexpected OCSP response in the server certificate")
772 }
773 if c.config.Bugs.NoSignedCertificateTimestamps && cert.sctList != nil {
774 c.sendAlert(alertUnsupportedExtension)
775 return errors.New("tls: unexpected SCT list in the server certificate")
776 }
777 if i > 0 && c.config.Bugs.ExpectNoExtensionsOnIntermediate && (cert.ocspResponse != nil || cert.sctList != nil) {
778 c.sendAlert(alertUnsupportedExtension)
779 return errors.New("tls: unexpected extensions in the server certificate")
780 }
781 }
782
Nick Harperb41d2e42016-07-01 17:50:32 -0400783 if err := hs.verifyCertificates(certMsg); err != nil {
784 return err
785 }
786 leaf := c.peerCertificates[0]
Steven Valdeza833c352016-11-01 13:39:36 -0400787 c.ocspResponse = certMsg.certificates[0].ocspResponse
788 c.sctList = certMsg.certificates[0].sctList
789
Nick Harperb41d2e42016-07-01 17:50:32 -0400790 msg, err = c.readHandshake()
791 if err != nil {
792 return err
793 }
794 certVerifyMsg, ok := msg.(*certificateVerifyMsg)
795 if !ok {
796 c.sendAlert(alertUnexpectedMessage)
797 return unexpectedMessageError(certVerifyMsg, msg)
798 }
799
David Benjaminf74ec792016-07-13 21:18:49 -0400800 c.peerSignatureAlgorithm = certVerifyMsg.signatureAlgorithm
Nick Harperb41d2e42016-07-01 17:50:32 -0400801 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
David Benjamin1fb125c2016-07-08 18:52:12 -0700802 err = verifyMessage(c.vers, leaf.PublicKey, c.config, certVerifyMsg.signatureAlgorithm, input, certVerifyMsg.signature)
Nick Harperb41d2e42016-07-01 17:50:32 -0400803 if err != nil {
804 return err
805 }
806
807 hs.writeServerHash(certVerifyMsg.marshal())
808 }
809
810 msg, err = c.readHandshake()
811 if err != nil {
812 return err
813 }
814 serverFinished, ok := msg.(*finishedMsg)
815 if !ok {
816 c.sendAlert(alertUnexpectedMessage)
817 return unexpectedMessageError(serverFinished, msg)
818 }
819
Steven Valdezc4aa7272016-10-03 12:25:56 -0400820 verify := hs.finishedHash.serverSum(serverHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400821 if len(verify) != len(serverFinished.verifyData) ||
822 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
823 c.sendAlert(alertHandshakeFailure)
824 return errors.New("tls: server's Finished message was incorrect")
825 }
826
827 hs.writeServerHash(serverFinished.marshal())
828
829 // The various secrets do not incorporate the client's final leg, so
830 // derive them now before updating the handshake context.
David Benjamin48891ad2016-12-04 00:02:43 -0500831 hs.finishedHash.addEntropy(zeroSecret)
832 clientTrafficSecret := hs.finishedHash.deriveSecret(clientApplicationTrafficLabel)
833 serverTrafficSecret := hs.finishedHash.deriveSecret(serverApplicationTrafficLabel)
Nick Harperb41d2e42016-07-01 17:50:32 -0400834
Steven Valdez0ee2e112016-07-15 06:51:15 -0400835 if certReq != nil && !c.config.Bugs.SkipClientCertificate {
David Benjamin8d343b42016-07-09 14:26:01 -0700836 certMsg := &certificateMsg{
837 hasRequestContext: true,
838 requestContext: certReq.requestContext,
839 }
840 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -0400841 for _, certData := range chainToSend.Certificate {
842 certMsg.certificates = append(certMsg.certificates, certificateEntry{
843 data: certData,
844 extraExtension: c.config.Bugs.SendExtensionOnCertificate,
845 })
846 }
David Benjamin8d343b42016-07-09 14:26:01 -0700847 }
848 hs.writeClientHash(certMsg.marshal())
849 c.writeRecord(recordTypeHandshake, certMsg.marshal())
850
851 if chainToSend != nil {
852 certVerify := &certificateVerifyMsg{
853 hasSignatureAlgorithm: true,
854 }
855
856 // Determine the hash to sign.
857 privKey := chainToSend.PrivateKey
858
859 var err error
860 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
861 if err != nil {
862 c.sendAlert(alertInternalError)
863 return err
864 }
865
866 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
867 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
868 if err != nil {
869 c.sendAlert(alertInternalError)
870 return err
871 }
Steven Valdez0ee2e112016-07-15 06:51:15 -0400872 if c.config.Bugs.SendSignatureAlgorithm != 0 {
873 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
874 }
David Benjamin8d343b42016-07-09 14:26:01 -0700875
876 hs.writeClientHash(certVerify.marshal())
877 c.writeRecord(recordTypeHandshake, certVerify.marshal())
878 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400879 }
880
Nick Harper60a85cb2016-09-23 16:25:11 -0700881 if encryptedExtensions.extensions.channelIDRequested {
882 channelIDHash := crypto.SHA256.New()
883 channelIDHash.Write(hs.finishedHash.certificateVerifyInput(channelIDContextTLS13))
884 channelIDMsgBytes, err := hs.writeChannelIDMessage(channelIDHash.Sum(nil))
885 if err != nil {
886 return err
887 }
888 hs.writeClientHash(channelIDMsgBytes)
889 c.writeRecord(recordTypeHandshake, channelIDMsgBytes)
890 }
891
Nick Harperb41d2e42016-07-01 17:50:32 -0400892 // Send a client Finished message.
893 finished := new(finishedMsg)
Steven Valdezc4aa7272016-10-03 12:25:56 -0400894 finished.verifyData = hs.finishedHash.clientSum(clientHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400895 if c.config.Bugs.BadFinished {
896 finished.verifyData[0]++
897 }
David Benjamin97a0a082016-07-13 17:57:35 -0400898 hs.writeClientHash(finished.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400899 if c.config.Bugs.PartialClientFinishedWithClientHello {
900 // The first byte has already been sent.
901 c.writeRecord(recordTypeHandshake, finished.marshal()[1:])
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500902 } else if c.config.Bugs.InterleaveEarlyData {
903 finishedBytes := finished.marshal()
904 c.sendFakeEarlyData(4)
905 c.writeRecord(recordTypeHandshake, finishedBytes[:1])
906 c.sendFakeEarlyData(4)
907 c.writeRecord(recordTypeHandshake, finishedBytes[1:])
David Benjamin7964b182016-07-14 23:36:30 -0400908 } else {
909 c.writeRecord(recordTypeHandshake, finished.marshal())
910 }
David Benjamin02edcd02016-07-27 17:40:37 -0400911 if c.config.Bugs.SendExtraFinished {
912 c.writeRecord(recordTypeHandshake, finished.marshal())
913 }
David Benjaminee51a222016-07-07 18:34:12 -0700914 c.flushHandshake()
Nick Harperb41d2e42016-07-01 17:50:32 -0400915
916 // Switch to application data keys.
Steven Valdeza833c352016-11-01 13:39:36 -0400917 c.out.useTrafficSecret(c.vers, hs.suite, clientTrafficSecret, clientWrite)
918 c.in.useTrafficSecret(c.vers, hs.suite, serverTrafficSecret, serverWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -0400919
David Benjamin48891ad2016-12-04 00:02:43 -0500920 c.exporterSecret = hs.finishedHash.deriveSecret(exporterLabel)
921 c.resumptionSecret = hs.finishedHash.deriveSecret(resumptionLabel)
Nick Harperb41d2e42016-07-01 17:50:32 -0400922 return nil
923}
924
Adam Langley95c29f32014-06-20 12:00:00 -0700925func (hs *clientHandshakeState) doFullHandshake() error {
926 c := hs.c
927
David Benjamin48cae082014-10-27 01:06:24 -0400928 var leaf *x509.Certificate
929 if hs.suite.flags&suitePSK == 0 {
930 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700931 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700932 return err
933 }
Adam Langley95c29f32014-06-20 12:00:00 -0700934
David Benjamin48cae082014-10-27 01:06:24 -0400935 certMsg, ok := msg.(*certificateMsg)
David Benjamin75051442016-07-01 18:58:51 -0400936 if !ok {
David Benjamin48cae082014-10-27 01:06:24 -0400937 c.sendAlert(alertUnexpectedMessage)
938 return unexpectedMessageError(certMsg, msg)
939 }
940 hs.writeServerHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700941
David Benjamin75051442016-07-01 18:58:51 -0400942 if err := hs.verifyCertificates(certMsg); err != nil {
943 return err
David Benjamin48cae082014-10-27 01:06:24 -0400944 }
David Benjamin75051442016-07-01 18:58:51 -0400945 leaf = c.peerCertificates[0]
David Benjamin48cae082014-10-27 01:06:24 -0400946 }
Adam Langley95c29f32014-06-20 12:00:00 -0700947
Nick Harperb3d51be2016-07-01 11:43:18 -0400948 if hs.serverHello.extensions.ocspStapling {
David Benjamin48cae082014-10-27 01:06:24 -0400949 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700950 if err != nil {
951 return err
952 }
953 cs, ok := msg.(*certificateStatusMsg)
954 if !ok {
955 c.sendAlert(alertUnexpectedMessage)
956 return unexpectedMessageError(cs, msg)
957 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400958 hs.writeServerHash(cs.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700959
960 if cs.statusType == statusTypeOCSP {
961 c.ocspResponse = cs.response
962 }
963 }
964
David Benjamin48cae082014-10-27 01:06:24 -0400965 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700966 if err != nil {
967 return err
968 }
969
970 keyAgreement := hs.suite.ka(c.vers)
971
972 skx, ok := msg.(*serverKeyExchangeMsg)
973 if ok {
David Benjamin83c0bc92014-08-04 01:23:53 -0400974 hs.writeServerHash(skx.marshal())
David Benjamin48cae082014-10-27 01:06:24 -0400975 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, leaf, skx)
Adam Langley95c29f32014-06-20 12:00:00 -0700976 if err != nil {
977 c.sendAlert(alertUnexpectedMessage)
978 return err
979 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400980 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
981 c.curveID = ecdhe.curveID
982 }
Adam Langley95c29f32014-06-20 12:00:00 -0700983
Nick Harper60edffd2016-06-21 15:19:24 -0700984 c.peerSignatureAlgorithm = keyAgreement.peerSignatureAlgorithm()
985
Adam Langley95c29f32014-06-20 12:00:00 -0700986 msg, err = c.readHandshake()
987 if err != nil {
988 return err
989 }
990 }
991
992 var chainToSend *Certificate
993 var certRequested bool
994 certReq, ok := msg.(*certificateRequestMsg)
995 if ok {
996 certRequested = true
David Benjamin7a41d372016-07-09 11:21:54 -0700997 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
998 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
999 }
Adam Langley95c29f32014-06-20 12:00:00 -07001000
David Benjamin83c0bc92014-08-04 01:23:53 -04001001 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001002
David Benjamina6f82632016-07-01 18:44:02 -04001003 chainToSend, err = selectClientCertificate(c, certReq)
1004 if err != nil {
1005 return err
Adam Langley95c29f32014-06-20 12:00:00 -07001006 }
1007
1008 msg, err = c.readHandshake()
1009 if err != nil {
1010 return err
1011 }
1012 }
1013
1014 shd, ok := msg.(*serverHelloDoneMsg)
1015 if !ok {
1016 c.sendAlert(alertUnexpectedMessage)
1017 return unexpectedMessageError(shd, msg)
1018 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001019 hs.writeServerHash(shd.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001020
1021 // If the server requested a certificate then we have to send a
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001022 // Certificate message in TLS, even if it's empty because we don't have
1023 // a certificate to send. In SSL 3.0, skip the message and send a
1024 // no_certificate warning alert.
Adam Langley95c29f32014-06-20 12:00:00 -07001025 if certRequested {
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001026 if c.vers == VersionSSL30 && chainToSend == nil {
1027 c.sendAlert(alertNoCertficate)
1028 } else if !c.config.Bugs.SkipClientCertificate {
1029 certMsg := new(certificateMsg)
1030 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -04001031 for _, certData := range chainToSend.Certificate {
1032 certMsg.certificates = append(certMsg.certificates, certificateEntry{
1033 data: certData,
1034 })
1035 }
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001036 }
1037 hs.writeClientHash(certMsg.marshal())
1038 c.writeRecord(recordTypeHandshake, certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001039 }
Adam Langley95c29f32014-06-20 12:00:00 -07001040 }
1041
David Benjamin48cae082014-10-27 01:06:24 -04001042 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, leaf)
Adam Langley95c29f32014-06-20 12:00:00 -07001043 if err != nil {
1044 c.sendAlert(alertInternalError)
1045 return err
1046 }
1047 if ckx != nil {
David Benjaminf3ec83d2014-07-21 22:42:34 -04001048 if c.config.Bugs.EarlyChangeCipherSpec < 2 {
David Benjamin83c0bc92014-08-04 01:23:53 -04001049 hs.writeClientHash(ckx.marshal())
David Benjaminf3ec83d2014-07-21 22:42:34 -04001050 }
Adam Langley95c29f32014-06-20 12:00:00 -07001051 c.writeRecord(recordTypeHandshake, ckx.marshal())
1052 }
1053
Nick Harperb3d51be2016-07-01 11:43:18 -04001054 if hs.serverHello.extensions.extendedMasterSecret && c.vers >= VersionTLS10 {
Adam Langley75712922014-10-10 16:23:43 -07001055 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1056 c.extendedMasterSecret = true
1057 } else {
1058 if c.config.Bugs.RequireExtendedMasterSecret {
1059 return errors.New("tls: extended master secret required but not supported by peer")
1060 }
1061 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
1062 }
David Benjamine098ec22014-08-27 23:13:20 -04001063
Adam Langley95c29f32014-06-20 12:00:00 -07001064 if chainToSend != nil {
Adam Langley95c29f32014-06-20 12:00:00 -07001065 certVerify := &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001066 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001067 }
1068
David Benjamin72dc7832015-03-16 17:49:43 -04001069 // Determine the hash to sign.
Nick Harper60edffd2016-06-21 15:19:24 -07001070 privKey := c.config.Certificates[0].PrivateKey
David Benjamin72dc7832015-03-16 17:49:43 -04001071
Nick Harper60edffd2016-06-21 15:19:24 -07001072 if certVerify.hasSignatureAlgorithm {
David Benjamin0a8deb22016-07-09 21:02:01 -07001073 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
Nick Harper60edffd2016-06-21 15:19:24 -07001074 if err != nil {
1075 c.sendAlert(alertInternalError)
1076 return err
Adam Langley95c29f32014-06-20 12:00:00 -07001077 }
Nick Harper60edffd2016-06-21 15:19:24 -07001078 }
1079
1080 if c.vers > VersionSSL30 {
David Benjamin5208fd42016-07-13 21:43:25 -04001081 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, hs.finishedHash.buffer)
David Benjamina95e9f32016-07-08 16:28:04 -07001082 if err == nil && c.config.Bugs.SendSignatureAlgorithm != 0 {
1083 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
1084 }
Nick Harper60edffd2016-06-21 15:19:24 -07001085 } else {
1086 // SSL 3.0's client certificate construction is
1087 // incompatible with signatureAlgorithm.
1088 rsaKey, ok := privKey.(*rsa.PrivateKey)
1089 if !ok {
1090 err = errors.New("unsupported signature type for client certificate")
1091 } else {
1092 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
David Benjamin5208fd42016-07-13 21:43:25 -04001093 if c.config.Bugs.InvalidSignature {
Nick Harper60edffd2016-06-21 15:19:24 -07001094 digest[0] ^= 0x80
1095 }
1096 certVerify.signature, err = rsa.SignPKCS1v15(c.config.rand(), rsaKey, crypto.MD5SHA1, digest)
1097 }
Adam Langley95c29f32014-06-20 12:00:00 -07001098 }
1099 if err != nil {
1100 c.sendAlert(alertInternalError)
1101 return errors.New("tls: failed to sign handshake with client certificate: " + err.Error())
1102 }
Adam Langley95c29f32014-06-20 12:00:00 -07001103
David Benjamin83c0bc92014-08-04 01:23:53 -04001104 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001105 c.writeRecord(recordTypeHandshake, certVerify.marshal())
1106 }
David Benjamin82261be2016-07-07 14:32:50 -07001107 // flushHandshake will be called in sendFinished.
Adam Langley95c29f32014-06-20 12:00:00 -07001108
David Benjamine098ec22014-08-27 23:13:20 -04001109 hs.finishedHash.discardHandshakeBuffer()
1110
Adam Langley95c29f32014-06-20 12:00:00 -07001111 return nil
1112}
1113
David Benjamin75051442016-07-01 18:58:51 -04001114func (hs *clientHandshakeState) verifyCertificates(certMsg *certificateMsg) error {
1115 c := hs.c
1116
1117 if len(certMsg.certificates) == 0 {
1118 c.sendAlert(alertIllegalParameter)
1119 return errors.New("tls: no certificates sent")
1120 }
1121
1122 certs := make([]*x509.Certificate, len(certMsg.certificates))
Steven Valdeza833c352016-11-01 13:39:36 -04001123 for i, certEntry := range certMsg.certificates {
1124 cert, err := x509.ParseCertificate(certEntry.data)
David Benjamin75051442016-07-01 18:58:51 -04001125 if err != nil {
1126 c.sendAlert(alertBadCertificate)
1127 return errors.New("tls: failed to parse certificate from server: " + err.Error())
1128 }
1129 certs[i] = cert
1130 }
1131
1132 if !c.config.InsecureSkipVerify {
1133 opts := x509.VerifyOptions{
1134 Roots: c.config.RootCAs,
1135 CurrentTime: c.config.time(),
1136 DNSName: c.config.ServerName,
1137 Intermediates: x509.NewCertPool(),
1138 }
1139
1140 for i, cert := range certs {
1141 if i == 0 {
1142 continue
1143 }
1144 opts.Intermediates.AddCert(cert)
1145 }
1146 var err error
1147 c.verifiedChains, err = certs[0].Verify(opts)
1148 if err != nil {
1149 c.sendAlert(alertBadCertificate)
1150 return err
1151 }
1152 }
1153
1154 switch certs[0].PublicKey.(type) {
1155 case *rsa.PublicKey, *ecdsa.PublicKey:
1156 break
1157 default:
1158 c.sendAlert(alertUnsupportedCertificate)
1159 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
1160 }
1161
1162 c.peerCertificates = certs
1163 return nil
1164}
1165
Adam Langley95c29f32014-06-20 12:00:00 -07001166func (hs *clientHandshakeState) establishKeys() error {
1167 c := hs.c
1168
1169 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001170 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 -07001171 var clientCipher, serverCipher interface{}
1172 var clientHash, serverHash macFunction
1173 if hs.suite.cipher != nil {
1174 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
1175 clientHash = hs.suite.mac(c.vers, clientMAC)
1176 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
1177 serverHash = hs.suite.mac(c.vers, serverMAC)
1178 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001179 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1180 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001181 }
1182
1183 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
1184 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
1185 return nil
1186}
1187
David Benjamin75101402016-07-01 13:40:23 -04001188func (hs *clientHandshakeState) processServerExtensions(serverExtensions *serverExtensions) error {
1189 c := hs.c
1190
David Benjamin8d315d72016-07-18 01:03:18 +02001191 if c.vers < VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001192 if c.config.Bugs.RequireRenegotiationInfo && serverExtensions.secureRenegotiation == nil {
1193 return errors.New("tls: renegotiation extension missing")
1194 }
David Benjamin75101402016-07-01 13:40:23 -04001195
Nick Harperb41d2e42016-07-01 17:50:32 -04001196 if len(c.clientVerify) > 0 && !c.noRenegotiationInfo() {
1197 var expectedRenegInfo []byte
1198 expectedRenegInfo = append(expectedRenegInfo, c.clientVerify...)
1199 expectedRenegInfo = append(expectedRenegInfo, c.serverVerify...)
1200 if !bytes.Equal(serverExtensions.secureRenegotiation, expectedRenegInfo) {
1201 c.sendAlert(alertHandshakeFailure)
1202 return fmt.Errorf("tls: renegotiation mismatch")
1203 }
David Benjamin75101402016-07-01 13:40:23 -04001204 }
David Benjamincea0ab42016-07-14 12:33:14 -04001205 } else if serverExtensions.secureRenegotiation != nil {
1206 return errors.New("tls: renegotiation info sent in TLS 1.3")
David Benjamin75101402016-07-01 13:40:23 -04001207 }
1208
1209 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
1210 if serverExtensions.customExtension != *expected {
1211 return fmt.Errorf("tls: bad custom extension contents %q", serverExtensions.customExtension)
1212 }
1213 }
1214
1215 clientDidNPN := hs.hello.nextProtoNeg
1216 clientDidALPN := len(hs.hello.alpnProtocols) > 0
1217 serverHasNPN := serverExtensions.nextProtoNeg
1218 serverHasALPN := len(serverExtensions.alpnProtocol) > 0
1219
1220 if !clientDidNPN && serverHasNPN {
1221 c.sendAlert(alertHandshakeFailure)
1222 return errors.New("server advertised unrequested NPN extension")
1223 }
1224
1225 if !clientDidALPN && serverHasALPN {
1226 c.sendAlert(alertHandshakeFailure)
1227 return errors.New("server advertised unrequested ALPN extension")
1228 }
1229
1230 if serverHasNPN && serverHasALPN {
1231 c.sendAlert(alertHandshakeFailure)
1232 return errors.New("server advertised both NPN and ALPN extensions")
1233 }
1234
1235 if serverHasALPN {
1236 c.clientProtocol = serverExtensions.alpnProtocol
1237 c.clientProtocolFallback = false
1238 c.usedALPN = true
1239 }
1240
David Benjamin8d315d72016-07-18 01:03:18 +02001241 if serverHasNPN && c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001242 c.sendAlert(alertHandshakeFailure)
1243 return errors.New("server advertised NPN over TLS 1.3")
1244 }
1245
David Benjamin75101402016-07-01 13:40:23 -04001246 if !hs.hello.channelIDSupported && serverExtensions.channelIDRequested {
1247 c.sendAlert(alertHandshakeFailure)
1248 return errors.New("server advertised unrequested Channel ID extension")
1249 }
1250
David Benjamin8d315d72016-07-18 01:03:18 +02001251 if serverExtensions.extendedMasterSecret && c.vers >= VersionTLS13 {
David Benjamine9077652016-07-13 21:02:08 -04001252 return errors.New("tls: server advertised extended master secret over TLS 1.3")
1253 }
1254
David Benjamin8d315d72016-07-18 01:03:18 +02001255 if serverExtensions.ticketSupported && c.vers >= VersionTLS13 {
Steven Valdez143e8b32016-07-11 13:19:03 -04001256 return errors.New("tls: server advertised ticket extension over TLS 1.3")
1257 }
1258
Steven Valdeza833c352016-11-01 13:39:36 -04001259 if serverExtensions.ocspStapling && c.vers >= VersionTLS13 {
1260 return errors.New("tls: server advertised OCSP in ServerHello over TLS 1.3")
1261 }
1262
David Benjamin53210cb2016-11-16 09:01:48 +09001263 if serverExtensions.ocspStapling && c.config.Bugs.NoOCSPStapling {
1264 return errors.New("tls: server advertised unrequested OCSP extension")
1265 }
1266
Steven Valdeza833c352016-11-01 13:39:36 -04001267 if len(serverExtensions.sctList) > 0 && c.vers >= VersionTLS13 {
1268 return errors.New("tls: server advertised SCTs in ServerHello over TLS 1.3")
1269 }
1270
David Benjamin53210cb2016-11-16 09:01:48 +09001271 if len(serverExtensions.sctList) > 0 && c.config.Bugs.NoSignedCertificateTimestamps {
1272 return errors.New("tls: server advertised unrequested SCTs")
1273 }
1274
David Benjamin75101402016-07-01 13:40:23 -04001275 if serverExtensions.srtpProtectionProfile != 0 {
1276 if serverExtensions.srtpMasterKeyIdentifier != "" {
1277 return errors.New("tls: server selected SRTP MKI value")
1278 }
1279
1280 found := false
1281 for _, p := range c.config.SRTPProtectionProfiles {
1282 if p == serverExtensions.srtpProtectionProfile {
1283 found = true
1284 break
1285 }
1286 }
1287 if !found {
1288 return errors.New("tls: server advertised unsupported SRTP profile")
1289 }
1290
1291 c.srtpProtectionProfile = serverExtensions.srtpProtectionProfile
1292 }
1293
1294 return nil
1295}
1296
Adam Langley95c29f32014-06-20 12:00:00 -07001297func (hs *clientHandshakeState) serverResumedSession() bool {
1298 // If the server responded with the same sessionId then it means the
1299 // sessionTicket is being used to resume a TLS session.
1300 return hs.session != nil && hs.hello.sessionId != nil &&
1301 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
1302}
1303
1304func (hs *clientHandshakeState) processServerHello() (bool, error) {
1305 c := hs.c
1306
David Benjamin6f600d62016-12-21 16:06:54 -05001307 if hs.serverHello.shortHeader {
1308 return false, errors.New("tls: short header extension sent before TLS 1.3")
1309 }
1310
Adam Langley95c29f32014-06-20 12:00:00 -07001311 if hs.serverResumedSession() {
David Benjamin4b27d9f2015-05-12 22:42:52 -04001312 // For test purposes, assert that the server never accepts the
1313 // resumption offer on renegotiation.
1314 if c.cipherSuite != nil && c.config.Bugs.FailIfResumeOnRenego {
1315 return false, errors.New("tls: server resumed session on renegotiation")
1316 }
1317
Nick Harperb3d51be2016-07-01 11:43:18 -04001318 if hs.serverHello.extensions.sctList != nil {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001319 return false, errors.New("tls: server sent SCT extension on session resumption")
1320 }
1321
Nick Harperb3d51be2016-07-01 11:43:18 -04001322 if hs.serverHello.extensions.ocspStapling {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001323 return false, errors.New("tls: server sent OCSP extension on session resumption")
1324 }
1325
Adam Langley95c29f32014-06-20 12:00:00 -07001326 // Restore masterSecret and peerCerts from previous state
1327 hs.masterSecret = hs.session.masterSecret
1328 c.peerCertificates = hs.session.serverCertificates
Adam Langley75712922014-10-10 16:23:43 -07001329 c.extendedMasterSecret = hs.session.extendedMasterSecret
Paul Lietar62be8ac2015-09-16 10:03:30 +01001330 c.sctList = hs.session.sctList
1331 c.ocspResponse = hs.session.ocspResponse
David Benjamine098ec22014-08-27 23:13:20 -04001332 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001333 return true, nil
1334 }
Paul Lietar62be8ac2015-09-16 10:03:30 +01001335
Nick Harperb3d51be2016-07-01 11:43:18 -04001336 if hs.serverHello.extensions.sctList != nil {
1337 c.sctList = hs.serverHello.extensions.sctList
Paul Lietar62be8ac2015-09-16 10:03:30 +01001338 }
1339
Adam Langley95c29f32014-06-20 12:00:00 -07001340 return false, nil
1341}
1342
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001343func (hs *clientHandshakeState) readFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001344 c := hs.c
1345
1346 c.readRecord(recordTypeChangeCipherSpec)
1347 if err := c.in.error(); err != nil {
1348 return err
1349 }
1350
1351 msg, err := c.readHandshake()
1352 if err != nil {
1353 return err
1354 }
1355 serverFinished, ok := msg.(*finishedMsg)
1356 if !ok {
1357 c.sendAlert(alertUnexpectedMessage)
1358 return unexpectedMessageError(serverFinished, msg)
1359 }
1360
David Benjaminf3ec83d2014-07-21 22:42:34 -04001361 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
1362 verify := hs.finishedHash.serverSum(hs.masterSecret)
1363 if len(verify) != len(serverFinished.verifyData) ||
1364 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
1365 c.sendAlert(alertHandshakeFailure)
1366 return errors.New("tls: server's Finished message was incorrect")
1367 }
Adam Langley95c29f32014-06-20 12:00:00 -07001368 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001369 c.serverVerify = append(c.serverVerify[:0], serverFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001370 copy(out, serverFinished.verifyData)
David Benjamin83c0bc92014-08-04 01:23:53 -04001371 hs.writeServerHash(serverFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001372 return nil
1373}
1374
1375func (hs *clientHandshakeState) readSessionTicket() error {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001376 c := hs.c
1377
1378 // Create a session with no server identifier. Either a
1379 // session ID or session ticket will be attached.
1380 session := &ClientSessionState{
1381 vers: c.vers,
1382 cipherSuite: hs.suite.id,
1383 masterSecret: hs.masterSecret,
Nick Harperc9846112016-10-17 15:05:35 -07001384 handshakeHash: hs.finishedHash.Sum(),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001385 serverCertificates: c.peerCertificates,
Paul Lietar62be8ac2015-09-16 10:03:30 +01001386 sctList: c.sctList,
1387 ocspResponse: c.ocspResponse,
Nick Harper0b3625b2016-07-25 16:16:28 -07001388 ticketExpiration: c.config.time().Add(time.Duration(7 * 24 * time.Hour)),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001389 }
1390
Nick Harperb3d51be2016-07-01 11:43:18 -04001391 if !hs.serverHello.extensions.ticketSupported {
David Benjamind98452d2015-06-16 14:16:23 -04001392 if c.config.Bugs.ExpectNewTicket {
1393 return errors.New("tls: expected new ticket")
1394 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001395 if hs.session == nil && len(hs.serverHello.sessionId) > 0 {
1396 session.sessionId = hs.serverHello.sessionId
1397 hs.session = session
1398 }
Adam Langley95c29f32014-06-20 12:00:00 -07001399 return nil
1400 }
1401
David Benjaminc7ce9772015-10-09 19:32:41 -04001402 if c.vers == VersionSSL30 {
1403 return errors.New("tls: negotiated session tickets in SSL 3.0")
1404 }
1405
Adam Langley95c29f32014-06-20 12:00:00 -07001406 msg, err := c.readHandshake()
1407 if err != nil {
1408 return err
1409 }
1410 sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
1411 if !ok {
1412 c.sendAlert(alertUnexpectedMessage)
1413 return unexpectedMessageError(sessionTicketMsg, msg)
1414 }
Adam Langley95c29f32014-06-20 12:00:00 -07001415
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001416 session.sessionTicket = sessionTicketMsg.ticket
1417 hs.session = session
Adam Langley95c29f32014-06-20 12:00:00 -07001418
David Benjamind30a9902014-08-24 01:44:23 -04001419 hs.writeServerHash(sessionTicketMsg.marshal())
1420
Adam Langley95c29f32014-06-20 12:00:00 -07001421 return nil
1422}
1423
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001424func (hs *clientHandshakeState) sendFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001425 c := hs.c
1426
David Benjamin0b8d5da2016-07-15 00:39:56 -04001427 var postCCSMsgs [][]byte
David Benjamin83c0bc92014-08-04 01:23:53 -04001428 seqno := hs.c.sendHandshakeSeq
Nick Harperb3d51be2016-07-01 11:43:18 -04001429 if hs.serverHello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001430 nextProto := new(nextProtoMsg)
Nick Harperb3d51be2016-07-01 11:43:18 -04001431 proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.extensions.nextProtos)
Adam Langley95c29f32014-06-20 12:00:00 -07001432 nextProto.proto = proto
1433 c.clientProtocol = proto
1434 c.clientProtocolFallback = fallback
1435
David Benjamin86271ee2014-07-21 16:14:03 -04001436 nextProtoBytes := nextProto.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -04001437 hs.writeHash(nextProtoBytes, seqno)
1438 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001439 postCCSMsgs = append(postCCSMsgs, nextProtoBytes)
Adam Langley95c29f32014-06-20 12:00:00 -07001440 }
1441
Nick Harperb3d51be2016-07-01 11:43:18 -04001442 if hs.serverHello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001443 var resumeHash []byte
1444 if isResume {
1445 resumeHash = hs.session.handshakeHash
1446 }
Nick Harper60a85cb2016-09-23 16:25:11 -07001447 channelIDMsgBytes, err := hs.writeChannelIDMessage(hs.finishedHash.hashForChannelID(resumeHash))
David Benjamind30a9902014-08-24 01:44:23 -04001448 if err != nil {
1449 return err
1450 }
David Benjamin24599a82016-06-30 18:56:53 -04001451 hs.writeHash(channelIDMsgBytes, seqno)
David Benjamind30a9902014-08-24 01:44:23 -04001452 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001453 postCCSMsgs = append(postCCSMsgs, channelIDMsgBytes)
David Benjamind30a9902014-08-24 01:44:23 -04001454 }
1455
Adam Langley95c29f32014-06-20 12:00:00 -07001456 finished := new(finishedMsg)
David Benjaminf3ec83d2014-07-21 22:42:34 -04001457 if c.config.Bugs.EarlyChangeCipherSpec == 2 {
1458 finished.verifyData = hs.finishedHash.clientSum(nil)
1459 } else {
1460 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
1461 }
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001462 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001463 if c.config.Bugs.BadFinished {
1464 finished.verifyData[0]++
1465 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001466 c.clientVerify = append(c.clientVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001467 hs.finishedBytes = finished.marshal()
1468 hs.writeHash(hs.finishedBytes, seqno)
David Benjamin0b8d5da2016-07-15 00:39:56 -04001469 postCCSMsgs = append(postCCSMsgs, hs.finishedBytes)
David Benjamin86271ee2014-07-21 16:14:03 -04001470
1471 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001472 c.writeRecord(recordTypeHandshake, postCCSMsgs[0][:5])
1473 postCCSMsgs[0] = postCCSMsgs[0][5:]
David Benjamin61672812016-07-14 23:10:43 -04001474 } else if c.config.Bugs.SendUnencryptedFinished {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001475 c.writeRecord(recordTypeHandshake, postCCSMsgs[0])
1476 postCCSMsgs = postCCSMsgs[1:]
David Benjamin86271ee2014-07-21 16:14:03 -04001477 }
David Benjamin582ba042016-07-07 12:33:25 -07001478 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001479
1480 if !c.config.Bugs.SkipChangeCipherSpec &&
1481 c.config.Bugs.EarlyChangeCipherSpec == 0 {
David Benjamin8411b242015-11-26 12:07:28 -05001482 ccs := []byte{1}
1483 if c.config.Bugs.BadChangeCipherSpec != nil {
1484 ccs = c.config.Bugs.BadChangeCipherSpec
1485 }
1486 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamin86271ee2014-07-21 16:14:03 -04001487 }
1488
David Benjamin4189bd92015-01-25 23:52:39 -05001489 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1490 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1491 }
David Benjamindc3da932015-03-12 15:09:02 -04001492 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1493 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1494 return errors.New("tls: simulating post-CCS alert")
1495 }
David Benjamin4189bd92015-01-25 23:52:39 -05001496
David Benjamin0b8d5da2016-07-15 00:39:56 -04001497 if !c.config.Bugs.SkipFinished {
1498 for _, msg := range postCCSMsgs {
1499 c.writeRecord(recordTypeHandshake, msg)
1500 }
David Benjamin02edcd02016-07-27 17:40:37 -04001501
1502 if c.config.Bugs.SendExtraFinished {
1503 c.writeRecord(recordTypeHandshake, finished.marshal())
1504 }
1505
David Benjamin582ba042016-07-07 12:33:25 -07001506 c.flushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -05001507 }
Adam Langley95c29f32014-06-20 12:00:00 -07001508 return nil
1509}
1510
Nick Harper60a85cb2016-09-23 16:25:11 -07001511func (hs *clientHandshakeState) writeChannelIDMessage(channelIDHash []byte) ([]byte, error) {
1512 c := hs.c
1513 channelIDMsg := new(channelIDMsg)
1514 if c.config.ChannelID.Curve != elliptic.P256() {
1515 return nil, fmt.Errorf("tls: Channel ID is not on P-256.")
1516 }
1517 r, s, err := ecdsa.Sign(c.config.rand(), c.config.ChannelID, channelIDHash)
1518 if err != nil {
1519 return nil, err
1520 }
1521 channelID := make([]byte, 128)
1522 writeIntPadded(channelID[0:32], c.config.ChannelID.X)
1523 writeIntPadded(channelID[32:64], c.config.ChannelID.Y)
1524 writeIntPadded(channelID[64:96], r)
1525 writeIntPadded(channelID[96:128], s)
1526 if c.config.Bugs.InvalidChannelIDSignature {
1527 channelID[64] ^= 1
1528 }
1529 channelIDMsg.channelID = channelID
1530
1531 c.channelID = &c.config.ChannelID.PublicKey
1532
1533 return channelIDMsg.marshal(), nil
1534}
1535
David Benjamin83c0bc92014-08-04 01:23:53 -04001536func (hs *clientHandshakeState) writeClientHash(msg []byte) {
1537 // writeClientHash is called before writeRecord.
1538 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1539}
1540
1541func (hs *clientHandshakeState) writeServerHash(msg []byte) {
1542 // writeServerHash is called after readHandshake.
1543 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1544}
1545
1546func (hs *clientHandshakeState) writeHash(msg []byte, seqno uint16) {
1547 if hs.c.isDTLS {
1548 // This is somewhat hacky. DTLS hashes a slightly different format.
1549 // First, the TLS header.
1550 hs.finishedHash.Write(msg[:4])
1551 // Then the sequence number and reassembled fragment offset (always 0).
1552 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1553 // Then the reassembled fragment (always equal to the message length).
1554 hs.finishedHash.Write(msg[1:4])
1555 // And then the message body.
1556 hs.finishedHash.Write(msg[4:])
1557 } else {
1558 hs.finishedHash.Write(msg)
1559 }
1560}
1561
David Benjamina6f82632016-07-01 18:44:02 -04001562// selectClientCertificate selects a certificate for use with the given
1563// certificate, or none if none match. It may return a particular certificate or
1564// nil on success, or an error on internal error.
1565func selectClientCertificate(c *Conn, certReq *certificateRequestMsg) (*Certificate, error) {
1566 // RFC 4346 on the certificateAuthorities field:
1567 // A list of the distinguished names of acceptable certificate
1568 // authorities. These distinguished names may specify a desired
1569 // distinguished name for a root CA or for a subordinate CA; thus, this
1570 // message can be used to describe both known roots and a desired
1571 // authorization space. If the certificate_authorities list is empty
1572 // then the client MAY send any certificate of the appropriate
1573 // ClientCertificateType, unless there is some external arrangement to
1574 // the contrary.
1575
1576 var rsaAvail, ecdsaAvail bool
Nick Harperb41d2e42016-07-01 17:50:32 -04001577 if !certReq.hasRequestContext {
1578 for _, certType := range certReq.certificateTypes {
1579 switch certType {
1580 case CertTypeRSASign:
1581 rsaAvail = true
1582 case CertTypeECDSASign:
1583 ecdsaAvail = true
1584 }
David Benjamina6f82632016-07-01 18:44:02 -04001585 }
1586 }
1587
1588 // We need to search our list of client certs for one
1589 // where SignatureAlgorithm is RSA and the Issuer is in
1590 // certReq.certificateAuthorities
1591findCert:
1592 for i, chain := range c.config.Certificates {
Nick Harperb41d2e42016-07-01 17:50:32 -04001593 if !certReq.hasRequestContext && !rsaAvail && !ecdsaAvail {
David Benjamina6f82632016-07-01 18:44:02 -04001594 continue
1595 }
1596
1597 // Ensure the private key supports one of the advertised
1598 // signature algorithms.
1599 if certReq.hasSignatureAlgorithm {
David Benjamin0a8deb22016-07-09 21:02:01 -07001600 if _, err := selectSignatureAlgorithm(c.vers, chain.PrivateKey, c.config, certReq.signatureAlgorithms); err != nil {
David Benjamina6f82632016-07-01 18:44:02 -04001601 continue
1602 }
1603 }
1604
1605 for j, cert := range chain.Certificate {
1606 x509Cert := chain.Leaf
1607 // parse the certificate if this isn't the leaf
1608 // node, or if chain.Leaf was nil
1609 if j != 0 || x509Cert == nil {
1610 var err error
1611 if x509Cert, err = x509.ParseCertificate(cert); err != nil {
1612 c.sendAlert(alertInternalError)
1613 return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
1614 }
1615 }
1616
Nick Harperb41d2e42016-07-01 17:50:32 -04001617 if !certReq.hasRequestContext {
1618 switch {
1619 case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
1620 case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
1621 default:
1622 continue findCert
1623 }
David Benjamina6f82632016-07-01 18:44:02 -04001624 }
1625
1626 if len(certReq.certificateAuthorities) == 0 {
1627 // They gave us an empty list, so just take the
1628 // first certificate of valid type from
1629 // c.config.Certificates.
1630 return &chain, nil
1631 }
1632
1633 for _, ca := range certReq.certificateAuthorities {
1634 if bytes.Equal(x509Cert.RawIssuer, ca) {
1635 return &chain, nil
1636 }
1637 }
1638 }
1639 }
1640
1641 return nil, nil
1642}
1643
Adam Langley95c29f32014-06-20 12:00:00 -07001644// clientSessionCacheKey returns a key used to cache sessionTickets that could
1645// be used to resume previously negotiated TLS sessions with a server.
1646func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
1647 if len(config.ServerName) > 0 {
1648 return config.ServerName
1649 }
1650 return serverAddr.String()
1651}
1652
David Benjaminfa055a22014-09-15 16:51:51 -04001653// mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
1654// given list of possible protocols and a list of the preference order. The
1655// first list must not be empty. It returns the resulting protocol and flag
Adam Langley95c29f32014-06-20 12:00:00 -07001656// indicating if the fallback case was reached.
David Benjaminfa055a22014-09-15 16:51:51 -04001657func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
1658 for _, s := range preferenceProtos {
1659 for _, c := range protos {
Adam Langley95c29f32014-06-20 12:00:00 -07001660 if s == c {
1661 return s, false
1662 }
1663 }
1664 }
1665
David Benjaminfa055a22014-09-15 16:51:51 -04001666 return protos[0], true
Adam Langley95c29f32014-06-20 12:00:00 -07001667}
David Benjamind30a9902014-08-24 01:44:23 -04001668
1669// writeIntPadded writes x into b, padded up with leading zeros as
1670// needed.
1671func writeIntPadded(b []byte, x *big.Int) {
1672 for i := range b {
1673 b[i] = 0
1674 }
1675 xb := x.Bytes()
1676 copy(b[len(b)-len(xb):], xb)
1677}
Steven Valdeza833c352016-11-01 13:39:36 -04001678
1679func generatePSKBinders(hello *clientHelloMsg, pskCipherSuite *cipherSuite, psk, transcript []byte, config *Config) {
1680 if config.Bugs.SendNoPSKBinder {
1681 return
1682 }
1683
1684 binderLen := pskCipherSuite.hash().Size()
1685 if config.Bugs.SendShortPSKBinder {
1686 binderLen--
1687 }
1688
David Benjaminaedf3032016-12-01 16:47:56 -05001689 numBinders := 1
1690 if config.Bugs.SendExtraPSKBinder {
1691 numBinders++
1692 }
1693
Steven Valdeza833c352016-11-01 13:39:36 -04001694 // Fill hello.pskBinders with appropriate length arrays of zeros so the
1695 // length prefixes are correct when computing the binder over the truncated
1696 // ClientHello message.
David Benjaminaedf3032016-12-01 16:47:56 -05001697 hello.pskBinders = make([][]byte, numBinders)
1698 for i := range hello.pskBinders {
Steven Valdeza833c352016-11-01 13:39:36 -04001699 hello.pskBinders[i] = make([]byte, binderLen)
1700 }
1701
1702 helloBytes := hello.marshal()
1703 binderSize := len(hello.pskBinders)*(binderLen+1) + 2
1704 truncatedHello := helloBytes[:len(helloBytes)-binderSize]
1705 binder := computePSKBinder(psk, resumptionPSKBinderLabel, pskCipherSuite, transcript, truncatedHello)
1706 if config.Bugs.SendShortPSKBinder {
1707 binder = binder[:binderLen]
1708 }
1709 if config.Bugs.SendInvalidPSKBinder {
1710 binder[0] ^= 1
1711 }
1712
1713 for i := range hello.pskBinders {
1714 hello.pskBinders[i] = binder
1715 }
1716
1717 hello.raw = nil
1718}