blob: 7b26cb6c59d3dd87f6c4b3872f541c8b64f2ceb5 [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 (
David Benjamin83c0bc92014-08-04 01:23:53 -04008 "bytes"
Adam Langley95c29f32014-06-20 12:00:00 -07009 "crypto"
10 "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 Benjamind30a9902014-08-24 01:44:23 -040018 "math/big"
Adam Langley95c29f32014-06-20 12:00:00 -070019)
20
21// serverHandshakeState contains details of a server handshake in progress.
22// It's discarded once the handshake has completed.
23type serverHandshakeState struct {
24 c *Conn
25 clientHello *clientHelloMsg
26 hello *serverHelloMsg
27 suite *cipherSuite
28 ellipticOk bool
29 ecdsaOk bool
30 sessionState *sessionState
31 finishedHash finishedHash
32 masterSecret []byte
33 certsFromClient [][]byte
34 cert *Certificate
David Benjamin83f90402015-01-27 01:09:43 -050035 finishedBytes []byte
Adam Langley95c29f32014-06-20 12:00:00 -070036}
37
38// serverHandshake performs a TLS handshake as a server.
39func (c *Conn) serverHandshake() error {
40 config := c.config
41
42 // If this is the first server handshake, we generate a random key to
43 // encrypt the tickets with.
44 config.serverInitOnce.Do(config.serverInit)
45
David Benjamin83c0bc92014-08-04 01:23:53 -040046 c.sendHandshakeSeq = 0
47 c.recvHandshakeSeq = 0
48
Adam Langley95c29f32014-06-20 12:00:00 -070049 hs := serverHandshakeState{
50 c: c,
51 }
David Benjaminf25dda92016-07-04 10:05:26 -070052 if err := hs.readClientHello(); err != nil {
53 return err
54 }
Adam Langley95c29f32014-06-20 12:00:00 -070055
David Benjamin8d315d72016-07-18 01:03:18 +020056 if c.vers >= VersionTLS13 {
Nick Harper728eed82016-07-07 17:36:52 -070057 if err := hs.doTLS13Handshake(); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -070058 return err
59 }
Nick Harper728eed82016-07-07 17:36:52 -070060 } else {
61 isResume, err := hs.processClientHello()
62 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -070063 return err
64 }
Nick Harper728eed82016-07-07 17:36:52 -070065
66 // For an overview of TLS handshaking, see https://tools.ietf.org/html/rfc5246#section-7.3
67 if isResume {
68 // The client has included a session ticket and so we do an abbreviated handshake.
69 if err := hs.doResumeHandshake(); err != nil {
70 return err
71 }
72 if err := hs.establishKeys(); err != nil {
73 return err
74 }
75 if c.config.Bugs.RenewTicketOnResume {
76 if err := hs.sendSessionTicket(); err != nil {
77 return err
78 }
79 }
80 if err := hs.sendFinished(c.firstFinished[:]); err != nil {
81 return err
82 }
83 // Most retransmits are triggered by a timeout, but the final
84 // leg of the handshake is retransmited upon re-receiving a
85 // Finished.
86 if err := c.simulatePacketLoss(func() {
David Benjamin02edcd02016-07-27 17:40:37 -040087 c.sendHandshakeSeq--
Nick Harper728eed82016-07-07 17:36:52 -070088 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
89 c.flushHandshake()
90 }); err != nil {
91 return err
92 }
93 if err := hs.readFinished(nil, isResume); err != nil {
94 return err
95 }
96 c.didResume = true
97 } else {
98 // The client didn't include a session ticket, or it wasn't
99 // valid so we do a full handshake.
100 if err := hs.doFullHandshake(); err != nil {
101 return err
102 }
103 if err := hs.establishKeys(); err != nil {
104 return err
105 }
106 if err := hs.readFinished(c.firstFinished[:], isResume); err != nil {
107 return err
108 }
109 if c.config.Bugs.AlertBeforeFalseStartTest != 0 {
110 c.sendAlert(c.config.Bugs.AlertBeforeFalseStartTest)
111 }
112 if c.config.Bugs.ExpectFalseStart {
113 if err := c.readRecord(recordTypeApplicationData); err != nil {
114 return fmt.Errorf("tls: peer did not false start: %s", err)
115 }
116 }
David Benjaminbed9aae2014-08-07 19:13:38 -0400117 if err := hs.sendSessionTicket(); err != nil {
118 return err
119 }
Nick Harper728eed82016-07-07 17:36:52 -0700120 if err := hs.sendFinished(nil); err != nil {
121 return err
David Benjamine58c4f52014-08-24 03:47:07 -0400122 }
123 }
David Benjamin97a0a082016-07-13 17:57:35 -0400124
125 c.exporterSecret = hs.masterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700126 }
127 c.handshakeComplete = true
David Benjaminc565ebb2015-04-03 04:06:36 -0400128 copy(c.clientRandom[:], hs.clientHello.random)
129 copy(c.serverRandom[:], hs.hello.random)
Adam Langley95c29f32014-06-20 12:00:00 -0700130
131 return nil
132}
133
David Benjaminf25dda92016-07-04 10:05:26 -0700134// readClientHello reads a ClientHello message from the client and determines
135// the protocol version.
136func (hs *serverHandshakeState) readClientHello() error {
Adam Langley95c29f32014-06-20 12:00:00 -0700137 config := hs.c.config
138 c := hs.c
139
David Benjamin83f90402015-01-27 01:09:43 -0500140 if err := c.simulatePacketLoss(nil); err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700141 return err
David Benjamin83f90402015-01-27 01:09:43 -0500142 }
Adam Langley95c29f32014-06-20 12:00:00 -0700143 msg, err := c.readHandshake()
144 if err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700145 return err
Adam Langley95c29f32014-06-20 12:00:00 -0700146 }
147 var ok bool
148 hs.clientHello, ok = msg.(*clientHelloMsg)
149 if !ok {
150 c.sendAlert(alertUnexpectedMessage)
David Benjaminf25dda92016-07-04 10:05:26 -0700151 return unexpectedMessageError(hs.clientHello, msg)
Adam Langley95c29f32014-06-20 12:00:00 -0700152 }
Adam Langley33ad2b52015-07-20 17:43:53 -0700153 if size := config.Bugs.RequireClientHelloSize; size != 0 && len(hs.clientHello.raw) != size {
David Benjaminf25dda92016-07-04 10:05:26 -0700154 return fmt.Errorf("tls: ClientHello record size is %d, but expected %d", len(hs.clientHello.raw), size)
Feng Lu41aa3252014-11-21 22:47:56 -0800155 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400156
157 if c.isDTLS && !config.Bugs.SkipHelloVerifyRequest {
David Benjamin8bc38f52014-08-16 12:07:27 -0400158 // Per RFC 6347, the version field in HelloVerifyRequest SHOULD
159 // be always DTLS 1.0
David Benjamin83c0bc92014-08-04 01:23:53 -0400160 helloVerifyRequest := &helloVerifyRequestMsg{
David Benjamin8bc38f52014-08-16 12:07:27 -0400161 vers: VersionTLS10,
David Benjamin83c0bc92014-08-04 01:23:53 -0400162 cookie: make([]byte, 32),
163 }
164 if _, err := io.ReadFull(c.config.rand(), helloVerifyRequest.cookie); err != nil {
165 c.sendAlert(alertInternalError)
David Benjaminf25dda92016-07-04 10:05:26 -0700166 return errors.New("dtls: short read from Rand: " + err.Error())
David Benjamin83c0bc92014-08-04 01:23:53 -0400167 }
168 c.writeRecord(recordTypeHandshake, helloVerifyRequest.marshal())
David Benjamin582ba042016-07-07 12:33:25 -0700169 c.flushHandshake()
David Benjamin83c0bc92014-08-04 01:23:53 -0400170
David Benjamin83f90402015-01-27 01:09:43 -0500171 if err := c.simulatePacketLoss(nil); err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700172 return err
David Benjamin83f90402015-01-27 01:09:43 -0500173 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400174 msg, err := c.readHandshake()
175 if err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700176 return err
David Benjamin83c0bc92014-08-04 01:23:53 -0400177 }
178 newClientHello, ok := msg.(*clientHelloMsg)
179 if !ok {
180 c.sendAlert(alertUnexpectedMessage)
David Benjaminf25dda92016-07-04 10:05:26 -0700181 return unexpectedMessageError(hs.clientHello, msg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400182 }
183 if !bytes.Equal(newClientHello.cookie, helloVerifyRequest.cookie) {
David Benjaminf25dda92016-07-04 10:05:26 -0700184 return errors.New("dtls: invalid cookie")
David Benjamin83c0bc92014-08-04 01:23:53 -0400185 }
David Benjaminf2fedef2014-08-16 01:37:34 -0400186
187 // Apart from the cookie, the two ClientHellos must
188 // match. Note that clientHello.equal compares the
189 // serialization, so we make a copy.
190 oldClientHelloCopy := *hs.clientHello
191 oldClientHelloCopy.raw = nil
192 oldClientHelloCopy.cookie = nil
193 newClientHelloCopy := *newClientHello
194 newClientHelloCopy.raw = nil
195 newClientHelloCopy.cookie = nil
196 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
David Benjaminf25dda92016-07-04 10:05:26 -0700197 return errors.New("dtls: retransmitted ClientHello does not match")
David Benjamin83c0bc92014-08-04 01:23:53 -0400198 }
199 hs.clientHello = newClientHello
200 }
201
David Benjaminc44b1df2014-11-23 12:11:01 -0500202 if config.Bugs.RequireSameRenegoClientVersion && c.clientVersion != 0 {
203 if c.clientVersion != hs.clientHello.vers {
David Benjaminf25dda92016-07-04 10:05:26 -0700204 return fmt.Errorf("tls: client offered different version on renego")
David Benjaminc44b1df2014-11-23 12:11:01 -0500205 }
206 }
Steven Valdezfdd10992016-09-15 16:27:05 -0400207
David Benjaminc44b1df2014-11-23 12:11:01 -0500208 c.clientVersion = hs.clientHello.vers
Steven Valdezfdd10992016-09-15 16:27:05 -0400209
210 // Convert the ClientHello wire version to a protocol version.
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400211 var clientVersion uint16
212 if c.isDTLS {
213 if hs.clientHello.vers <= 0xfefd {
214 clientVersion = VersionTLS12
215 } else if hs.clientHello.vers <= 0xfeff {
216 clientVersion = VersionTLS10
217 }
218 } else {
Steven Valdezfdd10992016-09-15 16:27:05 -0400219 if hs.clientHello.vers >= VersionTLS12 {
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400220 clientVersion = VersionTLS12
221 } else if hs.clientHello.vers >= VersionTLS11 {
222 clientVersion = VersionTLS11
223 } else if hs.clientHello.vers >= VersionTLS10 {
224 clientVersion = VersionTLS10
225 } else if hs.clientHello.vers >= VersionSSL30 {
226 clientVersion = VersionSSL30
227 }
228 }
229
230 if config.Bugs.NegotiateVersion != 0 {
231 c.vers = config.Bugs.NegotiateVersion
232 } else if c.haveVers && config.Bugs.NegotiateVersionOnRenego != 0 {
233 c.vers = config.Bugs.NegotiateVersionOnRenego
Steven Valdezfdd10992016-09-15 16:27:05 -0400234 } else if len(hs.clientHello.supportedVersions) > 0 {
235 // Use the versions extension if supplied.
David Benjamind9791bf2016-09-27 16:39:52 -0400236 var foundVersion, foundGREASE bool
Steven Valdezfdd10992016-09-15 16:27:05 -0400237 for _, extVersion := range hs.clientHello.supportedVersions {
David Benjamind9791bf2016-09-27 16:39:52 -0400238 if isGREASEValue(extVersion) {
239 foundGREASE = true
240 }
Steven Valdezfdd10992016-09-15 16:27:05 -0400241 extVersion, ok = wireToVersion(extVersion, c.isDTLS)
242 if !ok {
243 continue
244 }
David Benjamind9791bf2016-09-27 16:39:52 -0400245 if config.isSupportedVersion(extVersion, c.isDTLS) && !foundVersion {
Steven Valdezfdd10992016-09-15 16:27:05 -0400246 c.vers = extVersion
247 foundVersion = true
248 break
249 }
250 }
251 if !foundVersion {
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400252 c.sendAlert(alertProtocolVersion)
Steven Valdezfdd10992016-09-15 16:27:05 -0400253 return errors.New("tls: client did not offer any supported protocol versions")
254 }
David Benjamind9791bf2016-09-27 16:39:52 -0400255 if config.Bugs.ExpectGREASE && !foundGREASE {
256 return errors.New("tls: no GREASE version value found")
257 }
Steven Valdezfdd10992016-09-15 16:27:05 -0400258 } else {
259 // Otherwise, use the legacy ClientHello version.
260 version := clientVersion
261 if maxVersion := config.maxVersion(c.isDTLS); version > maxVersion {
262 version = maxVersion
263 }
264 if version == 0 || !config.isSupportedVersion(version, c.isDTLS) {
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400265 return fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
266 }
Steven Valdezfdd10992016-09-15 16:27:05 -0400267 c.vers = version
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400268 }
269 c.haveVers = true
David Benjaminc44b1df2014-11-23 12:11:01 -0500270
David Benjamin6ae7f072015-01-26 10:22:13 -0500271 // Reject < 1.2 ClientHellos with signature_algorithms.
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400272 if clientVersion < VersionTLS12 && len(hs.clientHello.signatureAlgorithms) > 0 {
David Benjaminf25dda92016-07-04 10:05:26 -0700273 return fmt.Errorf("tls: client included signature_algorithms before TLS 1.2")
David Benjamin72dc7832015-03-16 17:49:43 -0400274 }
David Benjamin6ae7f072015-01-26 10:22:13 -0500275
David Benjaminf93995b2015-11-05 18:23:20 -0500276 // Check the client cipher list is consistent with the version.
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400277 if clientVersion < VersionTLS12 {
David Benjaminf93995b2015-11-05 18:23:20 -0500278 for _, id := range hs.clientHello.cipherSuites {
279 if isTLS12Cipher(id) {
David Benjaminf25dda92016-07-04 10:05:26 -0700280 return fmt.Errorf("tls: client offered TLS 1.2 cipher before TLS 1.2")
David Benjaminf93995b2015-11-05 18:23:20 -0500281 }
282 }
283 }
284
David Benjamin405da482016-08-08 17:25:07 -0400285 if config.Bugs.ExpectNoTLS12Session {
286 if len(hs.clientHello.sessionId) > 0 {
287 return fmt.Errorf("tls: client offered an unexpected session ID")
288 }
289 if len(hs.clientHello.sessionTicket) > 0 {
290 return fmt.Errorf("tls: client offered an unexpected session ticket")
291 }
292 }
293
294 if config.Bugs.ExpectNoTLS13PSK && len(hs.clientHello.pskIdentities) > 0 {
295 return fmt.Errorf("tls: client offered unexpected PSK identities")
296 }
297
David Benjamin65ac9972016-09-02 21:35:25 -0400298 var scsvFound, greaseFound bool
David Benjaminf25dda92016-07-04 10:05:26 -0700299 for _, cipherSuite := range hs.clientHello.cipherSuites {
300 if cipherSuite == fallbackSCSV {
301 scsvFound = true
David Benjamin65ac9972016-09-02 21:35:25 -0400302 }
303 if isGREASEValue(cipherSuite) {
304 greaseFound = true
David Benjaminf25dda92016-07-04 10:05:26 -0700305 }
306 }
307
308 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
309 return errors.New("tls: no fallback SCSV found when expected")
310 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
311 return errors.New("tls: fallback SCSV found when not expected")
312 }
313
David Benjamin65ac9972016-09-02 21:35:25 -0400314 if !greaseFound && config.Bugs.ExpectGREASE {
315 return errors.New("tls: no GREASE cipher suite value found")
316 }
317
318 greaseFound = false
319 for _, curve := range hs.clientHello.supportedCurves {
320 if isGREASEValue(uint16(curve)) {
321 greaseFound = true
322 break
323 }
324 }
325
326 if !greaseFound && config.Bugs.ExpectGREASE {
327 return errors.New("tls: no GREASE curve value found")
328 }
329
330 if len(hs.clientHello.keyShares) > 0 {
331 greaseFound = false
332 for _, keyShare := range hs.clientHello.keyShares {
333 if isGREASEValue(uint16(keyShare.group)) {
334 greaseFound = true
335 break
336 }
337 }
338
339 if !greaseFound && config.Bugs.ExpectGREASE {
340 return errors.New("tls: no GREASE curve value found")
341 }
342 }
343
David Benjaminf25dda92016-07-04 10:05:26 -0700344 if config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
David Benjamin7a41d372016-07-09 11:21:54 -0700345 hs.clientHello.signatureAlgorithms = config.signSignatureAlgorithms()
David Benjaminf25dda92016-07-04 10:05:26 -0700346 }
347 if config.Bugs.IgnorePeerCurvePreferences {
348 hs.clientHello.supportedCurves = config.curvePreferences()
349 }
350 if config.Bugs.IgnorePeerCipherPreferences {
351 hs.clientHello.cipherSuites = config.cipherSuites()
352 }
353
354 return nil
355}
356
Nick Harper728eed82016-07-07 17:36:52 -0700357func (hs *serverHandshakeState) doTLS13Handshake() error {
358 c := hs.c
359 config := c.config
360
361 hs.hello = &serverHelloMsg{
David Benjamin490469f2016-10-05 22:44:38 -0400362 isDTLS: c.isDTLS,
363 vers: versionToWire(c.vers, c.isDTLS),
364 versOverride: config.Bugs.SendServerHelloVersion,
365 customExtension: config.Bugs.CustomUnencryptedExtension,
366 unencryptedALPN: config.Bugs.SendUnencryptedALPN,
Steven Valdez5440fe02016-07-18 12:40:30 -0400367 }
368
Nick Harper728eed82016-07-07 17:36:52 -0700369 hs.hello.random = make([]byte, 32)
370 if _, err := io.ReadFull(config.rand(), hs.hello.random); err != nil {
371 c.sendAlert(alertInternalError)
372 return err
373 }
374
375 // TLS 1.3 forbids clients from advertising any non-null compression.
376 if len(hs.clientHello.compressionMethods) != 1 || hs.clientHello.compressionMethods[0] != compressionNone {
377 return errors.New("tls: client sent compression method other than null for TLS 1.3")
378 }
379
380 // Prepare an EncryptedExtensions message, but do not send it yet.
381 encryptedExtensions := new(encryptedExtensionsMsg)
Steven Valdez143e8b32016-07-11 13:19:03 -0400382 encryptedExtensions.empty = config.Bugs.EmptyEncryptedExtensions
Nick Harper728eed82016-07-07 17:36:52 -0700383 if err := hs.processClientExtensions(&encryptedExtensions.extensions); err != nil {
384 return err
385 }
386
387 supportedCurve := false
388 var selectedCurve CurveID
389 preferredCurves := config.curvePreferences()
390Curves:
391 for _, curve := range hs.clientHello.supportedCurves {
392 for _, supported := range preferredCurves {
393 if supported == curve {
394 supportedCurve = true
395 selectedCurve = curve
396 break Curves
397 }
398 }
399 }
400
Steven Valdez803c77a2016-09-06 14:13:43 -0400401 if !supportedCurve {
402 c.sendAlert(alertHandshakeFailure)
403 return errors.New("tls: no curve supported by both client and server")
404 }
Nick Harper728eed82016-07-07 17:36:52 -0700405
David Benjamin405da482016-08-08 17:25:07 -0400406 pskIdentities := hs.clientHello.pskIdentities
407 if len(pskIdentities) == 0 && len(hs.clientHello.sessionTicket) > 0 && c.config.Bugs.AcceptAnySession {
Steven Valdez5b986082016-09-01 12:29:49 -0400408 psk := pskIdentity{
409 keModes: []byte{pskDHEKEMode},
410 authModes: []byte{pskAuthMode},
411 ticket: hs.clientHello.sessionTicket,
412 }
413 pskIdentities = []pskIdentity{psk}
David Benjamin405da482016-08-08 17:25:07 -0400414 }
415 for i, pskIdentity := range pskIdentities {
Steven Valdez5b986082016-09-01 12:29:49 -0400416 foundKE := false
417 foundAuth := false
418
419 for _, keMode := range pskIdentity.keModes {
420 if keMode == pskDHEKEMode {
421 foundKE = true
422 }
423 }
424
425 for _, authMode := range pskIdentity.authModes {
426 if authMode == pskAuthMode {
427 foundAuth = true
428 }
429 }
430
431 if !foundKE || !foundAuth {
432 continue
433 }
434
435 sessionState, ok := c.decryptTicket(pskIdentity.ticket)
Nick Harper0b3625b2016-07-25 16:16:28 -0700436 if !ok {
437 continue
438 }
Steven Valdez803c77a2016-09-06 14:13:43 -0400439 if config.Bugs.AcceptAnySession {
440 // Replace the cipher suite with one known to work, to
441 // test cross-version resumption attempts.
442 sessionState.cipherSuite = TLS_AES_128_GCM_SHA256
443 } else {
David Benjamin405da482016-08-08 17:25:07 -0400444 if sessionState.vers != c.vers && c.config.Bugs.AcceptAnySession {
445 continue
446 }
David Benjamin405da482016-08-08 17:25:07 -0400447 if sessionState.ticketExpiration.Before(c.config.time()) {
448 continue
449 }
David Benjamin405da482016-08-08 17:25:07 -0400450
Steven Valdez803c77a2016-09-06 14:13:43 -0400451 cipherSuiteOk := false
452 // Check that the client is still offering the ciphersuite in the session.
453 for _, id := range hs.clientHello.cipherSuites {
454 if id == sessionState.cipherSuite {
455 cipherSuiteOk = true
456 break
457 }
458 }
459 if !cipherSuiteOk {
460 continue
Nick Harper0b3625b2016-07-25 16:16:28 -0700461 }
462 }
David Benjamin405da482016-08-08 17:25:07 -0400463
Steven Valdez803c77a2016-09-06 14:13:43 -0400464 // Check that we also support the ciphersuite from the session.
465 suite := c.tryCipherSuite(sessionState.cipherSuite, c.config.cipherSuites(), c.vers, true, true)
466 if suite == nil {
467 continue
Nick Harper0b3625b2016-07-25 16:16:28 -0700468 }
Steven Valdez803c77a2016-09-06 14:13:43 -0400469
470 hs.sessionState = sessionState
471 hs.suite = suite
472 hs.hello.hasPSKIdentity = true
473 hs.hello.pskIdentity = uint16(i)
David Benjamin7f78df42016-10-05 22:33:19 -0400474 if config.Bugs.SelectPSKIdentityOnResume != 0 {
475 hs.hello.pskIdentity = config.Bugs.SelectPSKIdentityOnResume
476 }
Steven Valdez803c77a2016-09-06 14:13:43 -0400477 c.didResume = true
478 break
Nick Harper728eed82016-07-07 17:36:52 -0700479 }
480
David Benjamin7f78df42016-10-05 22:33:19 -0400481 if config.Bugs.AlwaysSelectPSKIdentity {
482 hs.hello.hasPSKIdentity = true
483 hs.hello.pskIdentity = 0
484 }
485
Nick Harper0b3625b2016-07-25 16:16:28 -0700486 // If not resuming, select the cipher suite.
487 if hs.suite == nil {
488 var preferenceList, supportedList []uint16
489 if config.PreferServerCipherSuites {
490 preferenceList = config.cipherSuites()
491 supportedList = hs.clientHello.cipherSuites
492 } else {
493 preferenceList = hs.clientHello.cipherSuites
494 supportedList = config.cipherSuites()
495 }
496
497 for _, id := range preferenceList {
Steven Valdez803c77a2016-09-06 14:13:43 -0400498 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, true, true); hs.suite != nil {
Nick Harper0b3625b2016-07-25 16:16:28 -0700499 break
500 }
Nick Harper728eed82016-07-07 17:36:52 -0700501 }
502 }
503
504 if hs.suite == nil {
505 c.sendAlert(alertHandshakeFailure)
506 return errors.New("tls: no cipher suite supported by both client and server")
507 }
508
509 hs.hello.cipherSuite = hs.suite.id
Steven Valdez0ee2e112016-07-15 06:51:15 -0400510 if c.config.Bugs.SendCipherSuite != 0 {
511 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
512 }
513
Nick Harper728eed82016-07-07 17:36:52 -0700514 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
515 hs.finishedHash.discardHandshakeBuffer()
516 hs.writeClientHash(hs.clientHello.marshal())
517
Steven Valdez803c77a2016-09-06 14:13:43 -0400518 hs.hello.useCertAuth = hs.sessionState == nil
519
Nick Harper728eed82016-07-07 17:36:52 -0700520 // Resolve PSK and compute the early secret.
Nick Harper0b3625b2016-07-25 16:16:28 -0700521 var psk []byte
Steven Valdez803c77a2016-09-06 14:13:43 -0400522 if hs.sessionState != nil {
Nick Harper0b3625b2016-07-25 16:16:28 -0700523 psk = deriveResumptionPSK(hs.suite, hs.sessionState.masterSecret)
524 hs.finishedHash.setResumptionContext(deriveResumptionContext(hs.suite, hs.sessionState.masterSecret))
525 } else {
526 psk = hs.finishedHash.zeroSecret()
527 hs.finishedHash.setResumptionContext(hs.finishedHash.zeroSecret())
528 }
Nick Harper728eed82016-07-07 17:36:52 -0700529
530 earlySecret := hs.finishedHash.extractKey(hs.finishedHash.zeroSecret(), psk)
531
Steven Valdez803c77a2016-09-06 14:13:43 -0400532 if config.Bugs.OmitServerHelloSignatureAlgorithms {
533 hs.hello.useCertAuth = false
534 } else if config.Bugs.IncludeServerHelloSignatureAlgorithms {
535 hs.hello.useCertAuth = true
536 }
537
538 hs.hello.hasKeyShare = true
539 if hs.sessionState != nil && config.Bugs.NegotiatePSKResumption {
540 hs.hello.hasKeyShare = false
541 }
542 if config.Bugs.MissingKeyShare {
543 hs.hello.hasKeyShare = false
544 }
545
Nick Harper728eed82016-07-07 17:36:52 -0700546 // Resolve ECDHE and compute the handshake secret.
547 var ecdheSecret []byte
Steven Valdez803c77a2016-09-06 14:13:43 -0400548 if hs.hello.hasKeyShare {
Nick Harper728eed82016-07-07 17:36:52 -0700549 // Look for the key share corresponding to our selected curve.
550 var selectedKeyShare *keyShareEntry
551 for i := range hs.clientHello.keyShares {
552 if hs.clientHello.keyShares[i].group == selectedCurve {
553 selectedKeyShare = &hs.clientHello.keyShares[i]
554 break
555 }
556 }
557
David Benjamine73c7f42016-08-17 00:29:33 -0400558 if config.Bugs.ExpectMissingKeyShare && selectedKeyShare != nil {
559 return errors.New("tls: expected missing key share")
560 }
561
Steven Valdez5440fe02016-07-18 12:40:30 -0400562 sendHelloRetryRequest := selectedKeyShare == nil
563 if config.Bugs.UnnecessaryHelloRetryRequest {
564 sendHelloRetryRequest = true
565 }
566 if config.Bugs.SkipHelloRetryRequest {
567 sendHelloRetryRequest = false
568 }
569 if sendHelloRetryRequest {
570 firstTime := true
571 ResendHelloRetryRequest:
Nick Harperdcfbc672016-07-16 17:47:31 +0200572 // Send HelloRetryRequest.
573 helloRetryRequestMsg := helloRetryRequestMsg{
Steven Valdezfdd10992016-09-15 16:27:05 -0400574 vers: versionToWire(c.vers, c.isDTLS),
Nick Harperdcfbc672016-07-16 17:47:31 +0200575 cipherSuite: hs.hello.cipherSuite,
576 selectedGroup: selectedCurve,
577 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400578 if config.Bugs.SendHelloRetryRequestCurve != 0 {
579 helloRetryRequestMsg.selectedGroup = config.Bugs.SendHelloRetryRequestCurve
580 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200581 hs.writeServerHash(helloRetryRequestMsg.marshal())
582 c.writeRecord(recordTypeHandshake, helloRetryRequestMsg.marshal())
David Benjamine73c7f42016-08-17 00:29:33 -0400583 c.flushHandshake()
Nick Harperdcfbc672016-07-16 17:47:31 +0200584
585 // Read new ClientHello.
586 newMsg, err := c.readHandshake()
587 if err != nil {
588 return err
589 }
590 newClientHello, ok := newMsg.(*clientHelloMsg)
591 if !ok {
592 c.sendAlert(alertUnexpectedMessage)
593 return unexpectedMessageError(newClientHello, newMsg)
594 }
595 hs.writeClientHash(newClientHello.marshal())
596
597 // Check that the new ClientHello matches the old ClientHello, except for
598 // the addition of the new KeyShareEntry at the end of the list, and
599 // removing the EarlyDataIndication extension (if present).
600 newKeyShares := newClientHello.keyShares
601 if len(newKeyShares) == 0 || newKeyShares[len(newKeyShares)-1].group != selectedCurve {
602 return errors.New("tls: KeyShare from HelloRetryRequest not present in new ClientHello")
603 }
604 oldClientHelloCopy := *hs.clientHello
605 oldClientHelloCopy.raw = nil
606 oldClientHelloCopy.hasEarlyData = false
607 oldClientHelloCopy.earlyDataContext = nil
608 newClientHelloCopy := *newClientHello
609 newClientHelloCopy.raw = nil
610 newClientHelloCopy.keyShares = newKeyShares[:len(newKeyShares)-1]
611 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
612 return errors.New("tls: new ClientHello does not match")
613 }
614
Steven Valdez5440fe02016-07-18 12:40:30 -0400615 if firstTime && config.Bugs.SecondHelloRetryRequest {
616 firstTime = false
617 goto ResendHelloRetryRequest
618 }
619
Nick Harperdcfbc672016-07-16 17:47:31 +0200620 selectedKeyShare = &newKeyShares[len(newKeyShares)-1]
Nick Harper728eed82016-07-07 17:36:52 -0700621 }
622
623 // Once a curve has been selected and a key share identified,
624 // the server needs to generate a public value and send it in
625 // the ServerHello.
Steven Valdez5440fe02016-07-18 12:40:30 -0400626 curve, ok := curveForCurveID(selectedCurve)
Nick Harper728eed82016-07-07 17:36:52 -0700627 if !ok {
628 panic("tls: server failed to look up curve ID")
629 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400630 c.curveID = selectedCurve
631
632 var peerKey []byte
633 if config.Bugs.SkipHelloRetryRequest {
634 // If skipping HelloRetryRequest, use a random key to
635 // avoid crashing.
636 curve2, _ := curveForCurveID(selectedCurve)
637 var err error
638 peerKey, err = curve2.offer(config.rand())
639 if err != nil {
640 return err
641 }
642 } else {
643 peerKey = selectedKeyShare.keyExchange
644 }
645
Nick Harper728eed82016-07-07 17:36:52 -0700646 var publicKey []byte
647 var err error
Steven Valdez5440fe02016-07-18 12:40:30 -0400648 publicKey, ecdheSecret, err = curve.accept(config.rand(), peerKey)
Nick Harper728eed82016-07-07 17:36:52 -0700649 if err != nil {
650 c.sendAlert(alertHandshakeFailure)
651 return err
652 }
653 hs.hello.hasKeyShare = true
Steven Valdez0ee2e112016-07-15 06:51:15 -0400654
Steven Valdez5440fe02016-07-18 12:40:30 -0400655 curveID := selectedCurve
Steven Valdez0ee2e112016-07-15 06:51:15 -0400656 if c.config.Bugs.SendCurve != 0 {
657 curveID = config.Bugs.SendCurve
658 }
659 if c.config.Bugs.InvalidECDHPoint {
660 publicKey[0] ^= 0xff
661 }
662
Nick Harper728eed82016-07-07 17:36:52 -0700663 hs.hello.keyShare = keyShareEntry{
Steven Valdez0ee2e112016-07-15 06:51:15 -0400664 group: curveID,
Nick Harper728eed82016-07-07 17:36:52 -0700665 keyExchange: publicKey,
666 }
Steven Valdez143e8b32016-07-11 13:19:03 -0400667
668 if config.Bugs.EncryptedExtensionsWithKeyShare {
669 encryptedExtensions.extensions.hasKeyShare = true
670 encryptedExtensions.extensions.keyShare = keyShareEntry{
671 group: curveID,
672 keyExchange: publicKey,
673 }
674 }
Nick Harper728eed82016-07-07 17:36:52 -0700675 } else {
676 ecdheSecret = hs.finishedHash.zeroSecret()
677 }
678
679 // Send unencrypted ServerHello.
680 hs.writeServerHash(hs.hello.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400681 if config.Bugs.PartialEncryptedExtensionsWithServerHello {
682 helloBytes := hs.hello.marshal()
683 toWrite := make([]byte, 0, len(helloBytes)+1)
684 toWrite = append(toWrite, helloBytes...)
685 toWrite = append(toWrite, typeEncryptedExtensions)
686 c.writeRecord(recordTypeHandshake, toWrite)
687 } else {
688 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
689 }
Nick Harper728eed82016-07-07 17:36:52 -0700690 c.flushHandshake()
691
692 // Compute the handshake secret.
693 handshakeSecret := hs.finishedHash.extractKey(earlySecret, ecdheSecret)
694
695 // Switch to handshake traffic keys.
Steven Valdezc4aa7272016-10-03 12:25:56 -0400696 serverHandshakeTrafficSecret := hs.finishedHash.deriveSecret(handshakeSecret, serverHandshakeTrafficLabel)
697 c.out.useTrafficSecret(c.vers, hs.suite, serverHandshakeTrafficSecret, handshakePhase, serverWrite)
698 clientHandshakeTrafficSecret := hs.finishedHash.deriveSecret(handshakeSecret, clientHandshakeTrafficLabel)
699 c.in.useTrafficSecret(c.vers, hs.suite, clientHandshakeTrafficSecret, handshakePhase, clientWrite)
Nick Harper728eed82016-07-07 17:36:52 -0700700
Steven Valdez803c77a2016-09-06 14:13:43 -0400701 if hs.hello.useCertAuth {
David Benjamin615119a2016-07-06 19:22:55 -0700702 if hs.clientHello.ocspStapling {
703 encryptedExtensions.extensions.ocspResponse = hs.cert.OCSPStaple
704 }
705 if hs.clientHello.sctListSupported {
706 encryptedExtensions.extensions.sctList = hs.cert.SignedCertificateTimestampList
707 }
David Benjamindaa88502016-10-04 16:32:16 -0400708 } else {
709 if config.Bugs.SendOCSPResponseOnResume != nil {
710 encryptedExtensions.extensions.ocspResponse = config.Bugs.SendOCSPResponseOnResume
711 }
712 if config.Bugs.SendSCTListOnResume != nil {
713 encryptedExtensions.extensions.sctList = config.Bugs.SendSCTListOnResume
714 }
David Benjamin615119a2016-07-06 19:22:55 -0700715 }
716
Nick Harper728eed82016-07-07 17:36:52 -0700717 // Send EncryptedExtensions.
718 hs.writeServerHash(encryptedExtensions.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400719 if config.Bugs.PartialEncryptedExtensionsWithServerHello {
720 // The first byte has already been sent.
721 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()[1:])
722 } else {
723 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal())
724 }
Nick Harper728eed82016-07-07 17:36:52 -0700725
Steven Valdez803c77a2016-09-06 14:13:43 -0400726 if hs.hello.useCertAuth {
Nick Harper728eed82016-07-07 17:36:52 -0700727 if config.ClientAuth >= RequestClientCert {
David Benjamin8d343b42016-07-09 14:26:01 -0700728 // Request a client certificate
729 certReq := &certificateRequestMsg{
730 hasSignatureAlgorithm: true,
731 hasRequestContext: true,
David Benjamin8a8349b2016-08-18 02:32:23 -0400732 requestContext: config.Bugs.SendRequestContext,
David Benjamin8d343b42016-07-09 14:26:01 -0700733 }
734 if !config.Bugs.NoSignatureAlgorithms {
David Benjaminf74ec792016-07-13 21:18:49 -0400735 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin8d343b42016-07-09 14:26:01 -0700736 }
737
738 // An empty list of certificateAuthorities signals to
739 // the client that it may send any certificate in response
740 // to our request. When we know the CAs we trust, then
741 // we can send them down, so that the client can choose
742 // an appropriate certificate to give to us.
743 if config.ClientCAs != nil {
744 certReq.certificateAuthorities = config.ClientCAs.Subjects()
745 }
746 hs.writeServerHash(certReq.marshal())
747 c.writeRecord(recordTypeHandshake, certReq.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700748 }
749
750 certMsg := &certificateMsg{
751 hasRequestContext: true,
752 }
753 if !config.Bugs.EmptyCertificateList {
754 certMsg.certificates = hs.cert.Certificate
755 }
David Benjamin1edae6b2016-07-13 16:58:23 -0400756 certMsgBytes := certMsg.marshal()
David Benjamin1edae6b2016-07-13 16:58:23 -0400757 hs.writeServerHash(certMsgBytes)
758 c.writeRecord(recordTypeHandshake, certMsgBytes)
Nick Harper728eed82016-07-07 17:36:52 -0700759
760 certVerify := &certificateVerifyMsg{
761 hasSignatureAlgorithm: true,
762 }
763
764 // Determine the hash to sign.
765 privKey := hs.cert.PrivateKey
766
767 var err error
768 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, config, hs.clientHello.signatureAlgorithms)
769 if err != nil {
770 c.sendAlert(alertInternalError)
771 return err
772 }
773
774 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
775 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
776 if err != nil {
777 c.sendAlert(alertInternalError)
778 return err
779 }
780
Steven Valdez0ee2e112016-07-15 06:51:15 -0400781 if config.Bugs.SendSignatureAlgorithm != 0 {
782 certVerify.signatureAlgorithm = config.Bugs.SendSignatureAlgorithm
783 }
784
Nick Harper728eed82016-07-07 17:36:52 -0700785 hs.writeServerHash(certVerify.marshal())
786 c.writeRecord(recordTypeHandshake, certVerify.marshal())
Steven Valdez803c77a2016-09-06 14:13:43 -0400787 } else if hs.sessionState != nil {
Nick Harper0b3625b2016-07-25 16:16:28 -0700788 // Pick up certificates from the session instead.
David Benjamin5ecb88b2016-10-04 17:51:35 -0400789 if len(hs.sessionState.certificates) > 0 {
Nick Harper0b3625b2016-07-25 16:16:28 -0700790 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
791 return err
792 }
793 }
Nick Harper728eed82016-07-07 17:36:52 -0700794 }
795
796 finished := new(finishedMsg)
Steven Valdezc4aa7272016-10-03 12:25:56 -0400797 finished.verifyData = hs.finishedHash.serverSum(serverHandshakeTrafficSecret)
Nick Harper728eed82016-07-07 17:36:52 -0700798 if config.Bugs.BadFinished {
799 finished.verifyData[0]++
800 }
801 hs.writeServerHash(finished.marshal())
802 c.writeRecord(recordTypeHandshake, finished.marshal())
David Benjamin02edcd02016-07-27 17:40:37 -0400803 if c.config.Bugs.SendExtraFinished {
804 c.writeRecord(recordTypeHandshake, finished.marshal())
805 }
Nick Harper728eed82016-07-07 17:36:52 -0700806 c.flushHandshake()
807
808 // The various secrets do not incorporate the client's final leg, so
809 // derive them now before updating the handshake context.
810 masterSecret := hs.finishedHash.extractKey(handshakeSecret, hs.finishedHash.zeroSecret())
Steven Valdezc4aa7272016-10-03 12:25:56 -0400811 clientTrafficSecret := hs.finishedHash.deriveSecret(masterSecret, clientApplicationTrafficLabel)
812 serverTrafficSecret := hs.finishedHash.deriveSecret(masterSecret, serverApplicationTrafficLabel)
Nick Harper728eed82016-07-07 17:36:52 -0700813
David Benjamin2aad4062016-07-14 23:15:40 -0400814 // Switch to application data keys on write. In particular, any alerts
815 // from the client certificate are sent over these keys.
Steven Valdezc4aa7272016-10-03 12:25:56 -0400816 c.out.useTrafficSecret(c.vers, hs.suite, serverTrafficSecret, applicationPhase, serverWrite)
David Benjamin2aad4062016-07-14 23:15:40 -0400817
Nick Harper728eed82016-07-07 17:36:52 -0700818 // If we requested a client certificate, then the client must send a
819 // certificate message, even if it's empty.
820 if config.ClientAuth >= RequestClientCert {
David Benjamin8d343b42016-07-09 14:26:01 -0700821 msg, err := c.readHandshake()
822 if err != nil {
823 return err
824 }
825
826 certMsg, ok := msg.(*certificateMsg)
827 if !ok {
828 c.sendAlert(alertUnexpectedMessage)
829 return unexpectedMessageError(certMsg, msg)
830 }
831 hs.writeClientHash(certMsg.marshal())
832
833 if len(certMsg.certificates) == 0 {
834 // The client didn't actually send a certificate
835 switch config.ClientAuth {
836 case RequireAnyClientCert, RequireAndVerifyClientCert:
David Benjamin1db9e1b2016-10-07 20:51:43 -0400837 c.sendAlert(alertCertificateRequired)
David Benjamin8d343b42016-07-09 14:26:01 -0700838 return errors.New("tls: client didn't provide a certificate")
839 }
840 }
841
842 pub, err := hs.processCertsFromClient(certMsg.certificates)
843 if err != nil {
844 return err
845 }
846
847 if len(c.peerCertificates) > 0 {
848 msg, err = c.readHandshake()
849 if err != nil {
850 return err
851 }
852
853 certVerify, ok := msg.(*certificateVerifyMsg)
854 if !ok {
855 c.sendAlert(alertUnexpectedMessage)
856 return unexpectedMessageError(certVerify, msg)
857 }
858
David Benjaminf74ec792016-07-13 21:18:49 -0400859 c.peerSignatureAlgorithm = certVerify.signatureAlgorithm
David Benjamin8d343b42016-07-09 14:26:01 -0700860 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
861 if err := verifyMessage(c.vers, pub, config, certVerify.signatureAlgorithm, input, certVerify.signature); err != nil {
862 c.sendAlert(alertBadCertificate)
863 return err
864 }
865 hs.writeClientHash(certVerify.marshal())
866 }
Nick Harper728eed82016-07-07 17:36:52 -0700867 }
868
869 // Read the client Finished message.
870 msg, err := c.readHandshake()
871 if err != nil {
872 return err
873 }
874 clientFinished, ok := msg.(*finishedMsg)
875 if !ok {
876 c.sendAlert(alertUnexpectedMessage)
877 return unexpectedMessageError(clientFinished, msg)
878 }
879
Steven Valdezc4aa7272016-10-03 12:25:56 -0400880 verify := hs.finishedHash.clientSum(clientHandshakeTrafficSecret)
Nick Harper728eed82016-07-07 17:36:52 -0700881 if len(verify) != len(clientFinished.verifyData) ||
882 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
883 c.sendAlert(alertHandshakeFailure)
884 return errors.New("tls: client's Finished message was incorrect")
885 }
David Benjamin97a0a082016-07-13 17:57:35 -0400886 hs.writeClientHash(clientFinished.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700887
David Benjamin2aad4062016-07-14 23:15:40 -0400888 // Switch to application data keys on read.
Steven Valdezc4aa7272016-10-03 12:25:56 -0400889 c.in.useTrafficSecret(c.vers, hs.suite, clientTrafficSecret, applicationPhase, clientWrite)
Nick Harper728eed82016-07-07 17:36:52 -0700890
Nick Harper728eed82016-07-07 17:36:52 -0700891 c.cipherSuite = hs.suite
David Benjamin97a0a082016-07-13 17:57:35 -0400892 c.exporterSecret = hs.finishedHash.deriveSecret(masterSecret, exporterLabel)
David Benjamin58104882016-07-18 01:25:41 +0200893 c.resumptionSecret = hs.finishedHash.deriveSecret(masterSecret, resumptionLabel)
894
895 // TODO(davidben): Allow configuring the number of tickets sent for
896 // testing.
897 if !c.config.SessionTicketsDisabled {
898 ticketCount := 2
899 for i := 0; i < ticketCount; i++ {
900 c.SendNewSessionTicket()
901 }
902 }
Nick Harper728eed82016-07-07 17:36:52 -0700903 return nil
904}
905
David Benjaminf25dda92016-07-04 10:05:26 -0700906// processClientHello processes the ClientHello message from the client and
907// decides whether we will perform session resumption.
908func (hs *serverHandshakeState) processClientHello() (isResume bool, err error) {
909 config := hs.c.config
910 c := hs.c
911
912 hs.hello = &serverHelloMsg{
913 isDTLS: c.isDTLS,
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400914 vers: versionToWire(c.vers, c.isDTLS),
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400915 versOverride: config.Bugs.SendServerHelloVersion,
David Benjaminf25dda92016-07-04 10:05:26 -0700916 compressionMethod: compressionNone,
917 }
918
919 hs.hello.random = make([]byte, 32)
920 _, err = io.ReadFull(config.rand(), hs.hello.random)
921 if err != nil {
922 c.sendAlert(alertInternalError)
923 return false, err
924 }
David Benjamin1f61f0d2016-07-10 12:20:35 -0400925 // Signal downgrades in the server random, per draft-ietf-tls-tls13-14,
926 // section 6.3.1.2.
Nick Harper85f20c22016-07-04 10:11:59 -0700927 if c.vers <= VersionTLS12 && config.maxVersion(c.isDTLS) >= VersionTLS13 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400928 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS13)
Nick Harper85f20c22016-07-04 10:11:59 -0700929 }
930 if c.vers <= VersionTLS11 && config.maxVersion(c.isDTLS) == VersionTLS12 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400931 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS12)
Nick Harper85f20c22016-07-04 10:11:59 -0700932 }
David Benjaminf25dda92016-07-04 10:05:26 -0700933
934 foundCompression := false
935 // We only support null compression, so check that the client offered it.
936 for _, compression := range hs.clientHello.compressionMethods {
937 if compression == compressionNone {
938 foundCompression = true
939 break
940 }
941 }
942
943 if !foundCompression {
944 c.sendAlert(alertHandshakeFailure)
945 return false, errors.New("tls: client does not support uncompressed connections")
946 }
David Benjamin7d79f832016-07-04 09:20:45 -0700947
948 if err := hs.processClientExtensions(&hs.hello.extensions); err != nil {
949 return false, err
Adam Langley09505632015-07-30 18:10:13 -0700950 }
Adam Langley95c29f32014-06-20 12:00:00 -0700951
952 supportedCurve := false
953 preferredCurves := config.curvePreferences()
954Curves:
955 for _, curve := range hs.clientHello.supportedCurves {
956 for _, supported := range preferredCurves {
957 if supported == curve {
958 supportedCurve = true
959 break Curves
960 }
961 }
962 }
963
964 supportedPointFormat := false
965 for _, pointFormat := range hs.clientHello.supportedPoints {
966 if pointFormat == pointFormatUncompressed {
967 supportedPointFormat = true
968 break
969 }
970 }
971 hs.ellipticOk = supportedCurve && supportedPointFormat
972
Adam Langley95c29f32014-06-20 12:00:00 -0700973 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
974
David Benjamin4b27d9f2015-05-12 22:42:52 -0400975 // For test purposes, check that the peer never offers a session when
976 // renegotiating.
977 if c.cipherSuite != nil && len(hs.clientHello.sessionId) > 0 && c.config.Bugs.FailIfResumeOnRenego {
978 return false, errors.New("tls: offered resumption on renegotiation")
979 }
980
David Benjamindd6fed92015-10-23 17:41:12 -0400981 if c.config.Bugs.FailIfSessionOffered && (len(hs.clientHello.sessionTicket) > 0 || len(hs.clientHello.sessionId) > 0) {
982 return false, errors.New("tls: client offered a session ticket or ID")
983 }
984
Adam Langley95c29f32014-06-20 12:00:00 -0700985 if hs.checkForResumption() {
986 return true, nil
987 }
988
Adam Langley95c29f32014-06-20 12:00:00 -0700989 var preferenceList, supportedList []uint16
990 if c.config.PreferServerCipherSuites {
991 preferenceList = c.config.cipherSuites()
992 supportedList = hs.clientHello.cipherSuites
993 } else {
994 preferenceList = hs.clientHello.cipherSuites
995 supportedList = c.config.cipherSuites()
996 }
997
998 for _, id := range preferenceList {
Steven Valdez803c77a2016-09-06 14:13:43 -0400999 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
Adam Langley95c29f32014-06-20 12:00:00 -07001000 break
1001 }
1002 }
1003
1004 if hs.suite == nil {
1005 c.sendAlert(alertHandshakeFailure)
1006 return false, errors.New("tls: no cipher suite supported by both client and server")
1007 }
1008
1009 return false, nil
1010}
1011
David Benjamin7d79f832016-07-04 09:20:45 -07001012// processClientExtensions processes all ClientHello extensions not directly
1013// related to cipher suite negotiation and writes responses in serverExtensions.
1014func (hs *serverHandshakeState) processClientExtensions(serverExtensions *serverExtensions) error {
1015 config := hs.c.config
1016 c := hs.c
1017
David Benjamin8d315d72016-07-18 01:03:18 +02001018 if c.vers < VersionTLS13 || config.Bugs.NegotiateRenegotiationInfoAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -07001019 if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) {
1020 c.sendAlert(alertHandshakeFailure)
1021 return errors.New("tls: renegotiation mismatch")
David Benjamin7d79f832016-07-04 09:20:45 -07001022 }
David Benjamin7d79f832016-07-04 09:20:45 -07001023
Nick Harper728eed82016-07-07 17:36:52 -07001024 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
1025 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.clientVerify...)
1026 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.serverVerify...)
1027 if c.config.Bugs.BadRenegotiationInfo {
1028 serverExtensions.secureRenegotiation[0] ^= 0x80
1029 }
1030 } else {
1031 serverExtensions.secureRenegotiation = hs.clientHello.secureRenegotiation
1032 }
1033
1034 if c.noRenegotiationInfo() {
1035 serverExtensions.secureRenegotiation = nil
1036 }
David Benjamin7d79f832016-07-04 09:20:45 -07001037 }
1038
1039 serverExtensions.duplicateExtension = c.config.Bugs.DuplicateExtension
1040
1041 if len(hs.clientHello.serverName) > 0 {
1042 c.serverName = hs.clientHello.serverName
1043 }
1044 if len(config.Certificates) == 0 {
1045 c.sendAlert(alertInternalError)
1046 return errors.New("tls: no certificates configured")
1047 }
1048 hs.cert = &config.Certificates[0]
1049 if len(hs.clientHello.serverName) > 0 {
1050 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
1051 }
1052 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
1053 return errors.New("tls: unexpected server name")
1054 }
1055
1056 if len(hs.clientHello.alpnProtocols) > 0 {
1057 if proto := c.config.Bugs.ALPNProtocol; proto != nil {
1058 serverExtensions.alpnProtocol = *proto
1059 serverExtensions.alpnProtocolEmpty = len(*proto) == 0
1060 c.clientProtocol = *proto
1061 c.usedALPN = true
1062 } else if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
1063 serverExtensions.alpnProtocol = selectedProto
1064 c.clientProtocol = selectedProto
1065 c.usedALPN = true
1066 }
1067 }
Nick Harper728eed82016-07-07 17:36:52 -07001068
David Benjamin0c40a962016-08-01 12:05:50 -04001069 if len(c.config.Bugs.SendALPN) > 0 {
1070 serverExtensions.alpnProtocol = c.config.Bugs.SendALPN
1071 }
1072
David Benjamin8d315d72016-07-18 01:03:18 +02001073 if c.vers < VersionTLS13 || config.Bugs.NegotiateNPNAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -07001074 if len(hs.clientHello.alpnProtocols) == 0 || c.config.Bugs.NegotiateALPNAndNPN {
1075 // Although sending an empty NPN extension is reasonable, Firefox has
1076 // had a bug around this. Best to send nothing at all if
1077 // config.NextProtos is empty. See
1078 // https://code.google.com/p/go/issues/detail?id=5445.
1079 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
1080 serverExtensions.nextProtoNeg = true
1081 serverExtensions.nextProtos = config.NextProtos
1082 serverExtensions.npnLast = config.Bugs.SwapNPNAndALPN
1083 }
David Benjamin7d79f832016-07-04 09:20:45 -07001084 }
Steven Valdez143e8b32016-07-11 13:19:03 -04001085 }
David Benjamin7d79f832016-07-04 09:20:45 -07001086
David Benjamin8d315d72016-07-18 01:03:18 +02001087 if c.vers < VersionTLS13 || config.Bugs.NegotiateEMSAtAllVersions {
David Benjamin163c9562016-08-29 23:14:17 -04001088 disableEMS := config.Bugs.NoExtendedMasterSecret
1089 if c.cipherSuite != nil {
1090 disableEMS = config.Bugs.NoExtendedMasterSecretOnRenegotiation
1091 }
1092 serverExtensions.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !disableEMS
Steven Valdez143e8b32016-07-11 13:19:03 -04001093 }
David Benjamin7d79f832016-07-04 09:20:45 -07001094
David Benjamin8d315d72016-07-18 01:03:18 +02001095 if c.vers < VersionTLS13 || config.Bugs.NegotiateChannelIDAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -07001096 if hs.clientHello.channelIDSupported && config.RequestChannelID {
1097 serverExtensions.channelIDRequested = true
1098 }
David Benjamin7d79f832016-07-04 09:20:45 -07001099 }
1100
1101 if hs.clientHello.srtpProtectionProfiles != nil {
1102 SRTPLoop:
1103 for _, p1 := range c.config.SRTPProtectionProfiles {
1104 for _, p2 := range hs.clientHello.srtpProtectionProfiles {
1105 if p1 == p2 {
1106 serverExtensions.srtpProtectionProfile = p1
1107 c.srtpProtectionProfile = p1
1108 break SRTPLoop
1109 }
1110 }
1111 }
1112 }
1113
1114 if c.config.Bugs.SendSRTPProtectionProfile != 0 {
1115 serverExtensions.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
1116 }
1117
1118 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
1119 if hs.clientHello.customExtension != *expected {
1120 return fmt.Errorf("tls: bad custom extension contents %q", hs.clientHello.customExtension)
1121 }
1122 }
1123 serverExtensions.customExtension = config.Bugs.CustomExtension
1124
Steven Valdez143e8b32016-07-11 13:19:03 -04001125 if c.config.Bugs.AdvertiseTicketExtension {
1126 serverExtensions.ticketSupported = true
1127 }
1128
David Benjamin65ac9972016-09-02 21:35:25 -04001129 if !hs.clientHello.hasGREASEExtension && config.Bugs.ExpectGREASE {
1130 return errors.New("tls: no GREASE extension found")
1131 }
1132
David Benjamin7d79f832016-07-04 09:20:45 -07001133 return nil
1134}
1135
Adam Langley95c29f32014-06-20 12:00:00 -07001136// checkForResumption returns true if we should perform resumption on this connection.
1137func (hs *serverHandshakeState) checkForResumption() bool {
1138 c := hs.c
1139
David Benjamin405da482016-08-08 17:25:07 -04001140 ticket := hs.clientHello.sessionTicket
1141 if len(ticket) == 0 && len(hs.clientHello.pskIdentities) > 0 && c.config.Bugs.AcceptAnySession {
Steven Valdez5b986082016-09-01 12:29:49 -04001142 ticket = hs.clientHello.pskIdentities[0].ticket
David Benjamin405da482016-08-08 17:25:07 -04001143 }
1144 if len(ticket) > 0 {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001145 if c.config.SessionTicketsDisabled {
1146 return false
1147 }
David Benjaminb0c8db72014-09-24 15:19:56 -04001148
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001149 var ok bool
David Benjamin405da482016-08-08 17:25:07 -04001150 if hs.sessionState, ok = c.decryptTicket(ticket); !ok {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001151 return false
1152 }
1153 } else {
1154 if c.config.ServerSessionCache == nil {
1155 return false
1156 }
1157
1158 var ok bool
1159 sessionId := string(hs.clientHello.sessionId)
1160 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
1161 return false
1162 }
Adam Langley95c29f32014-06-20 12:00:00 -07001163 }
1164
Steven Valdez803c77a2016-09-06 14:13:43 -04001165 if c.config.Bugs.AcceptAnySession {
1166 // Replace the cipher suite with one known to work, to test
1167 // cross-version resumption attempts.
1168 hs.sessionState.cipherSuite = TLS_RSA_WITH_AES_128_CBC_SHA
1169 } else {
David Benjamin405da482016-08-08 17:25:07 -04001170 // Never resume a session for a different SSL version.
1171 if c.vers != hs.sessionState.vers {
1172 return false
Adam Langley95c29f32014-06-20 12:00:00 -07001173 }
David Benjamin405da482016-08-08 17:25:07 -04001174
1175 cipherSuiteOk := false
1176 // Check that the client is still offering the ciphersuite in the session.
1177 for _, id := range hs.clientHello.cipherSuites {
1178 if id == hs.sessionState.cipherSuite {
1179 cipherSuiteOk = true
1180 break
1181 }
1182 }
1183 if !cipherSuiteOk {
1184 return false
1185 }
Adam Langley95c29f32014-06-20 12:00:00 -07001186 }
1187
1188 // Check that we also support the ciphersuite from the session.
Steven Valdez803c77a2016-09-06 14:13:43 -04001189 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), c.vers, hs.ellipticOk, hs.ecdsaOk)
1190
Adam Langley95c29f32014-06-20 12:00:00 -07001191 if hs.suite == nil {
1192 return false
1193 }
1194
1195 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
1196 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
1197 if needClientCerts && !sessionHasClientCerts {
1198 return false
1199 }
1200 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
1201 return false
1202 }
1203
1204 return true
1205}
1206
1207func (hs *serverHandshakeState) doResumeHandshake() error {
1208 c := hs.c
1209
1210 hs.hello.cipherSuite = hs.suite.id
David Benjaminece3de92015-03-16 18:02:20 -04001211 if c.config.Bugs.SendCipherSuite != 0 {
1212 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
1213 }
Adam Langley95c29f32014-06-20 12:00:00 -07001214 // We echo the client's session ID in the ServerHello to let it know
1215 // that we're doing a resumption.
1216 hs.hello.sessionId = hs.clientHello.sessionId
Nick Harperb3d51be2016-07-01 11:43:18 -04001217 hs.hello.extensions.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -07001218
David Benjamin80d1b352016-05-04 19:19:06 -04001219 if c.config.Bugs.SendSCTListOnResume != nil {
Nick Harperb3d51be2016-07-01 11:43:18 -04001220 hs.hello.extensions.sctList = c.config.Bugs.SendSCTListOnResume
David Benjamin80d1b352016-05-04 19:19:06 -04001221 }
1222
David Benjamindaa88502016-10-04 16:32:16 -04001223 if c.config.Bugs.SendOCSPResponseOnResume != nil {
1224 // There is no way, syntactically, to send an OCSP response on a
1225 // resumption handshake.
1226 hs.hello.extensions.ocspStapling = true
1227 }
1228
Adam Langley95c29f32014-06-20 12:00:00 -07001229 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -04001230 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -04001231 hs.writeClientHash(hs.clientHello.marshal())
1232 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001233
1234 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
1235
1236 if len(hs.sessionState.certificates) > 0 {
1237 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
1238 return err
1239 }
1240 }
1241
1242 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -07001243 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -07001244
1245 return nil
1246}
1247
1248func (hs *serverHandshakeState) doFullHandshake() error {
1249 config := hs.c.config
1250 c := hs.c
1251
David Benjamin48cae082014-10-27 01:06:24 -04001252 isPSK := hs.suite.flags&suitePSK != 0
1253 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001254 hs.hello.extensions.ocspStapling = true
Adam Langley95c29f32014-06-20 12:00:00 -07001255 }
1256
David Benjamin61f95272014-11-25 01:55:35 -05001257 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001258 hs.hello.extensions.sctList = hs.cert.SignedCertificateTimestampList
David Benjamin61f95272014-11-25 01:55:35 -05001259 }
1260
Nick Harperb3d51be2016-07-01 11:43:18 -04001261 hs.hello.extensions.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
Adam Langley95c29f32014-06-20 12:00:00 -07001262 hs.hello.cipherSuite = hs.suite.id
David Benjamin6095de82014-12-27 01:50:38 -05001263 if config.Bugs.SendCipherSuite != 0 {
1264 hs.hello.cipherSuite = config.Bugs.SendCipherSuite
1265 }
Nick Harperb3d51be2016-07-01 11:43:18 -04001266 c.extendedMasterSecret = hs.hello.extensions.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -07001267
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001268 // Generate a session ID if we're to save the session.
Nick Harperb3d51be2016-07-01 11:43:18 -04001269 if !hs.hello.extensions.ticketSupported && config.ServerSessionCache != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001270 hs.hello.sessionId = make([]byte, 32)
1271 if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
1272 c.sendAlert(alertInternalError)
1273 return errors.New("tls: short read from Rand: " + err.Error())
1274 }
1275 }
1276
Adam Langley95c29f32014-06-20 12:00:00 -07001277 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -04001278 hs.writeClientHash(hs.clientHello.marshal())
1279 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001280
David Benjaminabe94e32016-09-04 14:18:58 -04001281 if config.Bugs.SendSNIWarningAlert {
1282 c.SendAlert(alertLevelWarning, alertUnrecognizedName)
1283 }
1284
Adam Langley95c29f32014-06-20 12:00:00 -07001285 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
1286
David Benjamin48cae082014-10-27 01:06:24 -04001287 if !isPSK {
1288 certMsg := new(certificateMsg)
David Benjamin8923c0b2015-06-07 11:42:34 -04001289 if !config.Bugs.EmptyCertificateList {
1290 certMsg.certificates = hs.cert.Certificate
1291 }
David Benjamin48cae082014-10-27 01:06:24 -04001292 if !config.Bugs.UnauthenticatedECDH {
David Benjaminbcb2d912015-02-24 23:45:43 -05001293 certMsgBytes := certMsg.marshal()
David Benjaminbcb2d912015-02-24 23:45:43 -05001294 hs.writeServerHash(certMsgBytes)
1295 c.writeRecord(recordTypeHandshake, certMsgBytes)
David Benjamin48cae082014-10-27 01:06:24 -04001296 }
David Benjamin1c375dd2014-07-12 00:48:23 -04001297 }
Adam Langley95c29f32014-06-20 12:00:00 -07001298
Nick Harperb3d51be2016-07-01 11:43:18 -04001299 if hs.hello.extensions.ocspStapling && !c.config.Bugs.SkipCertificateStatus {
Adam Langley95c29f32014-06-20 12:00:00 -07001300 certStatus := new(certificateStatusMsg)
1301 certStatus.statusType = statusTypeOCSP
1302 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -04001303 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001304 c.writeRecord(recordTypeHandshake, certStatus.marshal())
1305 }
1306
1307 keyAgreement := hs.suite.ka(c.vers)
1308 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
1309 if err != nil {
1310 c.sendAlert(alertHandshakeFailure)
1311 return err
1312 }
Steven Valdez5440fe02016-07-18 12:40:30 -04001313 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
1314 c.curveID = ecdhe.curveID
1315 }
David Benjamin9c651c92014-07-12 13:27:45 -04001316 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -04001317 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001318 c.writeRecord(recordTypeHandshake, skx.marshal())
1319 }
1320
1321 if config.ClientAuth >= RequestClientCert {
1322 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -04001323 certReq := &certificateRequestMsg{
1324 certificateTypes: config.ClientCertificateTypes,
1325 }
1326 if certReq.certificateTypes == nil {
1327 certReq.certificateTypes = []byte{
1328 byte(CertTypeRSASign),
1329 byte(CertTypeECDSASign),
1330 }
Adam Langley95c29f32014-06-20 12:00:00 -07001331 }
1332 if c.vers >= VersionTLS12 {
Nick Harper60edffd2016-06-21 15:19:24 -07001333 certReq.hasSignatureAlgorithm = true
1334 if !config.Bugs.NoSignatureAlgorithms {
David Benjamin7a41d372016-07-09 11:21:54 -07001335 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin000800a2014-11-14 01:43:59 -05001336 }
Adam Langley95c29f32014-06-20 12:00:00 -07001337 }
1338
1339 // An empty list of certificateAuthorities signals to
1340 // the client that it may send any certificate in response
1341 // to our request. When we know the CAs we trust, then
1342 // we can send them down, so that the client can choose
1343 // an appropriate certificate to give to us.
1344 if config.ClientCAs != nil {
1345 certReq.certificateAuthorities = config.ClientCAs.Subjects()
1346 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001347 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001348 c.writeRecord(recordTypeHandshake, certReq.marshal())
1349 }
1350
1351 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001352 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001353 c.writeRecord(recordTypeHandshake, helloDone.marshal())
David Benjamin582ba042016-07-07 12:33:25 -07001354 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001355
1356 var pub crypto.PublicKey // public key for client auth, if any
1357
David Benjamin83f90402015-01-27 01:09:43 -05001358 if err := c.simulatePacketLoss(nil); err != nil {
1359 return err
1360 }
Adam Langley95c29f32014-06-20 12:00:00 -07001361 msg, err := c.readHandshake()
1362 if err != nil {
1363 return err
1364 }
1365
1366 var ok bool
1367 // If we requested a client certificate, then the client must send a
1368 // certificate message, even if it's empty.
1369 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -04001370 var certMsg *certificateMsg
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001371 var certificates [][]byte
1372 if certMsg, ok = msg.(*certificateMsg); ok {
1373 if c.vers == VersionSSL30 && len(certMsg.certificates) == 0 {
1374 return errors.New("tls: empty certificate message in SSL 3.0")
1375 }
1376
1377 hs.writeClientHash(certMsg.marshal())
1378 certificates = certMsg.certificates
1379 } else if c.vers != VersionSSL30 {
1380 // In TLS, the Certificate message is required. In SSL
1381 // 3.0, the peer skips it when sending no certificates.
Adam Langley95c29f32014-06-20 12:00:00 -07001382 c.sendAlert(alertUnexpectedMessage)
1383 return unexpectedMessageError(certMsg, msg)
1384 }
Adam Langley95c29f32014-06-20 12:00:00 -07001385
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001386 if len(certificates) == 0 {
Adam Langley95c29f32014-06-20 12:00:00 -07001387 // The client didn't actually send a certificate
1388 switch config.ClientAuth {
1389 case RequireAnyClientCert, RequireAndVerifyClientCert:
1390 c.sendAlert(alertBadCertificate)
1391 return errors.New("tls: client didn't provide a certificate")
1392 }
1393 }
1394
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001395 pub, err = hs.processCertsFromClient(certificates)
Adam Langley95c29f32014-06-20 12:00:00 -07001396 if err != nil {
1397 return err
1398 }
1399
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001400 if ok {
1401 msg, err = c.readHandshake()
1402 if err != nil {
1403 return err
1404 }
Adam Langley95c29f32014-06-20 12:00:00 -07001405 }
1406 }
1407
1408 // Get client key exchange
1409 ckx, ok := msg.(*clientKeyExchangeMsg)
1410 if !ok {
1411 c.sendAlert(alertUnexpectedMessage)
1412 return unexpectedMessageError(ckx, msg)
1413 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001414 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001415
David Benjamine098ec22014-08-27 23:13:20 -04001416 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
1417 if err != nil {
1418 c.sendAlert(alertHandshakeFailure)
1419 return err
1420 }
Adam Langley75712922014-10-10 16:23:43 -07001421 if c.extendedMasterSecret {
1422 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1423 } else {
1424 if c.config.Bugs.RequireExtendedMasterSecret {
1425 return errors.New("tls: extended master secret required but not supported by peer")
1426 }
1427 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
1428 }
David Benjamine098ec22014-08-27 23:13:20 -04001429
Adam Langley95c29f32014-06-20 12:00:00 -07001430 // If we received a client cert in response to our certificate request message,
1431 // the client will send us a certificateVerifyMsg immediately after the
1432 // clientKeyExchangeMsg. This message is a digest of all preceding
1433 // handshake-layer messages that is signed using the private key corresponding
1434 // to the client's certificate. This allows us to verify that the client is in
1435 // possession of the private key of the certificate.
1436 if len(c.peerCertificates) > 0 {
1437 msg, err = c.readHandshake()
1438 if err != nil {
1439 return err
1440 }
1441 certVerify, ok := msg.(*certificateVerifyMsg)
1442 if !ok {
1443 c.sendAlert(alertUnexpectedMessage)
1444 return unexpectedMessageError(certVerify, msg)
1445 }
1446
David Benjaminde620d92014-07-18 15:03:41 -04001447 // Determine the signature type.
Nick Harper60edffd2016-06-21 15:19:24 -07001448 var sigAlg signatureAlgorithm
1449 if certVerify.hasSignatureAlgorithm {
1450 sigAlg = certVerify.signatureAlgorithm
Nick Harper60edffd2016-06-21 15:19:24 -07001451 c.peerSignatureAlgorithm = sigAlg
David Benjaminde620d92014-07-18 15:03:41 -04001452 }
1453
Nick Harper60edffd2016-06-21 15:19:24 -07001454 if c.vers > VersionSSL30 {
David Benjamin1fb125c2016-07-08 18:52:12 -07001455 err = verifyMessage(c.vers, pub, c.config, sigAlg, hs.finishedHash.buffer, certVerify.signature)
Nick Harper60edffd2016-06-21 15:19:24 -07001456 } else {
1457 // SSL 3.0's client certificate construction is
1458 // incompatible with signatureAlgorithm.
1459 rsaPub, ok := pub.(*rsa.PublicKey)
1460 if !ok {
1461 err = errors.New("unsupported key type for client certificate")
1462 } else {
1463 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
1464 err = rsa.VerifyPKCS1v15(rsaPub, crypto.MD5SHA1, digest, certVerify.signature)
David Benjaminde620d92014-07-18 15:03:41 -04001465 }
Adam Langley95c29f32014-06-20 12:00:00 -07001466 }
1467 if err != nil {
1468 c.sendAlert(alertBadCertificate)
1469 return errors.New("could not validate signature of connection nonces: " + err.Error())
1470 }
1471
David Benjamin83c0bc92014-08-04 01:23:53 -04001472 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001473 }
1474
David Benjamine098ec22014-08-27 23:13:20 -04001475 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001476
1477 return nil
1478}
1479
1480func (hs *serverHandshakeState) establishKeys() error {
1481 c := hs.c
1482
1483 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001484 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen(c.vers))
Adam Langley95c29f32014-06-20 12:00:00 -07001485
1486 var clientCipher, serverCipher interface{}
1487 var clientHash, serverHash macFunction
1488
1489 if hs.suite.aead == nil {
1490 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
1491 clientHash = hs.suite.mac(c.vers, clientMAC)
1492 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
1493 serverHash = hs.suite.mac(c.vers, serverMAC)
1494 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001495 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1496 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001497 }
1498
1499 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
1500 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
1501
1502 return nil
1503}
1504
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001505func (hs *serverHandshakeState) readFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001506 c := hs.c
1507
1508 c.readRecord(recordTypeChangeCipherSpec)
1509 if err := c.in.error(); err != nil {
1510 return err
1511 }
1512
Nick Harperb3d51be2016-07-01 11:43:18 -04001513 if hs.hello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001514 msg, err := c.readHandshake()
1515 if err != nil {
1516 return err
1517 }
1518 nextProto, ok := msg.(*nextProtoMsg)
1519 if !ok {
1520 c.sendAlert(alertUnexpectedMessage)
1521 return unexpectedMessageError(nextProto, msg)
1522 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001523 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001524 c.clientProtocol = nextProto.proto
1525 }
1526
Nick Harperb3d51be2016-07-01 11:43:18 -04001527 if hs.hello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001528 msg, err := c.readHandshake()
1529 if err != nil {
1530 return err
1531 }
David Benjamin24599a82016-06-30 18:56:53 -04001532 channelIDMsg, ok := msg.(*channelIDMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001533 if !ok {
1534 c.sendAlert(alertUnexpectedMessage)
David Benjamin24599a82016-06-30 18:56:53 -04001535 return unexpectedMessageError(channelIDMsg, msg)
David Benjamind30a9902014-08-24 01:44:23 -04001536 }
David Benjamin24599a82016-06-30 18:56:53 -04001537 x := new(big.Int).SetBytes(channelIDMsg.channelID[0:32])
1538 y := new(big.Int).SetBytes(channelIDMsg.channelID[32:64])
1539 r := new(big.Int).SetBytes(channelIDMsg.channelID[64:96])
1540 s := new(big.Int).SetBytes(channelIDMsg.channelID[96:128])
David Benjamind30a9902014-08-24 01:44:23 -04001541 if !elliptic.P256().IsOnCurve(x, y) {
1542 return errors.New("tls: invalid channel ID public key")
1543 }
1544 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
1545 var resumeHash []byte
1546 if isResume {
1547 resumeHash = hs.sessionState.handshakeHash
1548 }
1549 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
1550 return errors.New("tls: invalid channel ID signature")
1551 }
1552 c.channelID = channelID
1553
David Benjamin24599a82016-06-30 18:56:53 -04001554 hs.writeClientHash(channelIDMsg.marshal())
David Benjamind30a9902014-08-24 01:44:23 -04001555 }
1556
Adam Langley95c29f32014-06-20 12:00:00 -07001557 msg, err := c.readHandshake()
1558 if err != nil {
1559 return err
1560 }
1561 clientFinished, ok := msg.(*finishedMsg)
1562 if !ok {
1563 c.sendAlert(alertUnexpectedMessage)
1564 return unexpectedMessageError(clientFinished, msg)
1565 }
1566
1567 verify := hs.finishedHash.clientSum(hs.masterSecret)
1568 if len(verify) != len(clientFinished.verifyData) ||
1569 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
1570 c.sendAlert(alertHandshakeFailure)
1571 return errors.New("tls: client's Finished message is incorrect")
1572 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001573 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001574 copy(out, clientFinished.verifyData)
Adam Langley95c29f32014-06-20 12:00:00 -07001575
David Benjamin83c0bc92014-08-04 01:23:53 -04001576 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001577 return nil
1578}
1579
1580func (hs *serverHandshakeState) sendSessionTicket() error {
Adam Langley95c29f32014-06-20 12:00:00 -07001581 c := hs.c
Adam Langley95c29f32014-06-20 12:00:00 -07001582 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -04001583 vers: c.vers,
1584 cipherSuite: hs.suite.id,
1585 masterSecret: hs.masterSecret,
1586 certificates: hs.certsFromClient,
1587 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -07001588 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001589
Nick Harperb3d51be2016-07-01 11:43:18 -04001590 if !hs.hello.extensions.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001591 if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
1592 c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
1593 }
1594 return nil
1595 }
1596
1597 m := new(newSessionTicketMsg)
1598
David Benjamindd6fed92015-10-23 17:41:12 -04001599 if !c.config.Bugs.SendEmptySessionTicket {
1600 var err error
1601 m.ticket, err = c.encryptTicket(&state)
1602 if err != nil {
1603 return err
1604 }
Adam Langley95c29f32014-06-20 12:00:00 -07001605 }
Adam Langley95c29f32014-06-20 12:00:00 -07001606
David Benjamin83c0bc92014-08-04 01:23:53 -04001607 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001608 c.writeRecord(recordTypeHandshake, m.marshal())
1609
1610 return nil
1611}
1612
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001613func (hs *serverHandshakeState) sendFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001614 c := hs.c
1615
David Benjamin86271ee2014-07-21 16:14:03 -04001616 finished := new(finishedMsg)
1617 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001618 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001619 if c.config.Bugs.BadFinished {
1620 finished.verifyData[0]++
1621 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001622 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001623 hs.finishedBytes = finished.marshal()
1624 hs.writeServerHash(hs.finishedBytes)
1625 postCCSBytes := hs.finishedBytes
David Benjamin86271ee2014-07-21 16:14:03 -04001626
1627 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
1628 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
1629 postCCSBytes = postCCSBytes[5:]
David Benjamin61672812016-07-14 23:10:43 -04001630 } else if c.config.Bugs.SendUnencryptedFinished {
1631 c.writeRecord(recordTypeHandshake, postCCSBytes)
1632 postCCSBytes = nil
David Benjamin86271ee2014-07-21 16:14:03 -04001633 }
David Benjamin582ba042016-07-07 12:33:25 -07001634 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001635
David Benjamina0e52232014-07-19 17:39:58 -04001636 if !c.config.Bugs.SkipChangeCipherSpec {
David Benjamin8411b242015-11-26 12:07:28 -05001637 ccs := []byte{1}
1638 if c.config.Bugs.BadChangeCipherSpec != nil {
1639 ccs = c.config.Bugs.BadChangeCipherSpec
1640 }
1641 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamina0e52232014-07-19 17:39:58 -04001642 }
Adam Langley95c29f32014-06-20 12:00:00 -07001643
David Benjamin4189bd92015-01-25 23:52:39 -05001644 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1645 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1646 }
David Benjamindc3da932015-03-12 15:09:02 -04001647 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1648 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1649 return errors.New("tls: simulating post-CCS alert")
1650 }
David Benjamin4189bd92015-01-25 23:52:39 -05001651
David Benjamin61672812016-07-14 23:10:43 -04001652 if !c.config.Bugs.SkipFinished && len(postCCSBytes) > 0 {
David Benjaminb80168e2015-02-08 18:30:14 -05001653 c.writeRecord(recordTypeHandshake, postCCSBytes)
David Benjamin02edcd02016-07-27 17:40:37 -04001654 if c.config.Bugs.SendExtraFinished {
1655 c.writeRecord(recordTypeHandshake, finished.marshal())
1656 }
1657
David Benjamin12d2c482016-07-24 10:56:51 -04001658 if !c.config.Bugs.PackHelloRequestWithFinished {
1659 // Defer flushing until renegotiation.
1660 c.flushHandshake()
1661 }
David Benjaminb3774b92015-01-31 17:16:01 -05001662 }
Adam Langley95c29f32014-06-20 12:00:00 -07001663
David Benjaminc565ebb2015-04-03 04:06:36 -04001664 c.cipherSuite = hs.suite
Adam Langley95c29f32014-06-20 12:00:00 -07001665
1666 return nil
1667}
1668
1669// processCertsFromClient takes a chain of client certificates either from a
1670// Certificates message or from a sessionState and verifies them. It returns
1671// the public key of the leaf certificate.
1672func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
1673 c := hs.c
1674
1675 hs.certsFromClient = certificates
1676 certs := make([]*x509.Certificate, len(certificates))
1677 var err error
1678 for i, asn1Data := range certificates {
1679 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
1680 c.sendAlert(alertBadCertificate)
1681 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
1682 }
1683 }
1684
1685 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
1686 opts := x509.VerifyOptions{
1687 Roots: c.config.ClientCAs,
1688 CurrentTime: c.config.time(),
1689 Intermediates: x509.NewCertPool(),
1690 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
1691 }
1692
1693 for _, cert := range certs[1:] {
1694 opts.Intermediates.AddCert(cert)
1695 }
1696
1697 chains, err := certs[0].Verify(opts)
1698 if err != nil {
1699 c.sendAlert(alertBadCertificate)
1700 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
1701 }
1702
1703 ok := false
1704 for _, ku := range certs[0].ExtKeyUsage {
1705 if ku == x509.ExtKeyUsageClientAuth {
1706 ok = true
1707 break
1708 }
1709 }
1710 if !ok {
1711 c.sendAlert(alertHandshakeFailure)
1712 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
1713 }
1714
1715 c.verifiedChains = chains
1716 }
1717
1718 if len(certs) > 0 {
1719 var pub crypto.PublicKey
1720 switch key := certs[0].PublicKey.(type) {
1721 case *ecdsa.PublicKey, *rsa.PublicKey:
1722 pub = key
1723 default:
1724 c.sendAlert(alertUnsupportedCertificate)
1725 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
1726 }
1727 c.peerCertificates = certs
1728 return pub, nil
1729 }
1730
1731 return nil, nil
1732}
1733
David Benjamin83c0bc92014-08-04 01:23:53 -04001734func (hs *serverHandshakeState) writeServerHash(msg []byte) {
1735 // writeServerHash is called before writeRecord.
1736 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1737}
1738
1739func (hs *serverHandshakeState) writeClientHash(msg []byte) {
1740 // writeClientHash is called after readHandshake.
1741 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1742}
1743
1744func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
1745 if hs.c.isDTLS {
1746 // This is somewhat hacky. DTLS hashes a slightly different format.
1747 // First, the TLS header.
1748 hs.finishedHash.Write(msg[:4])
1749 // Then the sequence number and reassembled fragment offset (always 0).
1750 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1751 // Then the reassembled fragment (always equal to the message length).
1752 hs.finishedHash.Write(msg[1:4])
1753 // And then the message body.
1754 hs.finishedHash.Write(msg[4:])
1755 } else {
1756 hs.finishedHash.Write(msg)
1757 }
1758}
1759
Adam Langley95c29f32014-06-20 12:00:00 -07001760// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
1761// is acceptable to use.
Steven Valdez803c77a2016-09-06 14:13:43 -04001762func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
Adam Langley95c29f32014-06-20 12:00:00 -07001763 for _, supported := range supportedCipherSuites {
1764 if id == supported {
1765 var candidate *cipherSuite
1766
1767 for _, s := range cipherSuites {
1768 if s.id == id {
1769 candidate = s
1770 break
1771 }
1772 }
1773 if candidate == nil {
1774 continue
1775 }
Steven Valdez803c77a2016-09-06 14:13:43 -04001776
Adam Langley95c29f32014-06-20 12:00:00 -07001777 // Don't select a ciphersuite which we can't
1778 // support for this client.
Steven Valdez803c77a2016-09-06 14:13:43 -04001779 if version >= VersionTLS13 || candidate.flags&suiteTLS13 != 0 {
1780 if version < VersionTLS13 || candidate.flags&suiteTLS13 == 0 {
1781 continue
1782 }
1783 return candidate
David Benjamin5ecb88b2016-10-04 17:51:35 -04001784 }
1785 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
1786 continue
1787 }
1788 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
1789 continue
1790 }
1791 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
1792 continue
1793 }
David Benjamin5ecb88b2016-10-04 17:51:35 -04001794 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
1795 continue
David Benjamin83c0bc92014-08-04 01:23:53 -04001796 }
Adam Langley95c29f32014-06-20 12:00:00 -07001797 return candidate
1798 }
1799 }
1800
1801 return nil
1802}
David Benjaminf93995b2015-11-05 18:23:20 -05001803
1804func isTLS12Cipher(id uint16) bool {
1805 for _, cipher := range cipherSuites {
1806 if cipher.id != id {
1807 continue
1808 }
1809 return cipher.flags&suiteTLS12 != 0
1810 }
1811 // Unknown cipher.
1812 return false
1813}
David Benjamin65ac9972016-09-02 21:35:25 -04001814
1815func isGREASEValue(val uint16) bool {
David Benjamin3c6a1ea2016-09-26 18:30:05 -04001816 return val&0x0f0f == 0x0a0a && val&0xff == val>>8
David Benjamin65ac9972016-09-02 21:35:25 -04001817}