1// 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 5package runner 6 7import ( 8 "bytes" 9 "crypto" 10 "crypto/ecdsa" 11 "crypto/elliptic" 12 "crypto/rsa" 13 "crypto/subtle" 14 "crypto/x509" 15 "errors" 16 "fmt" 17 "io" 18 "math/big" 19 "time" 20) 21 22// serverHandshakeState contains details of a server handshake in progress. 23// It's discarded once the handshake has completed. 24type serverHandshakeState struct { 25 c *Conn 26 clientHello *clientHelloMsg 27 hello *serverHelloMsg 28 suite *cipherSuite 29 ellipticOk bool 30 ecdsaOk bool 31 sessionState *sessionState 32 finishedHash finishedHash 33 masterSecret []byte 34 certsFromClient [][]byte 35 cert *Certificate 36 finishedBytes []byte 37} 38 39// serverHandshake performs a TLS handshake as a server. 40func (c *Conn) serverHandshake() error { 41 config := c.config 42 43 // If this is the first server handshake, we generate a random key to 44 // encrypt the tickets with. 45 config.serverInitOnce.Do(config.serverInit) 46 47 c.sendHandshakeSeq = 0 48 c.recvHandshakeSeq = 0 49 50 hs := serverHandshakeState{ 51 c: c, 52 } 53 if err := hs.readClientHello(); err != nil { 54 return err 55 } 56 57 if c.vers >= VersionTLS13 { 58 if err := hs.doTLS13Handshake(); err != nil { 59 return err 60 } 61 } else { 62 isResume, err := hs.processClientHello() 63 if err != nil { 64 return err 65 } 66 67 // For an overview of TLS handshaking, see https://tools.ietf.org/html/rfc5246#section-7.3 68 if isResume { 69 // The client has included a session ticket and so we do an abbreviated handshake. 70 if err := hs.doResumeHandshake(); err != nil { 71 return err 72 } 73 if err := hs.establishKeys(); err != nil { 74 return err 75 } 76 if c.config.Bugs.RenewTicketOnResume { 77 if err := hs.sendSessionTicket(); err != nil { 78 return err 79 } 80 } 81 if err := hs.sendFinished(c.firstFinished[:]); err != nil { 82 return err 83 } 84 // Most retransmits are triggered by a timeout, but the final 85 // leg of the handshake is retransmited upon re-receiving a 86 // Finished. 87 if err := c.simulatePacketLoss(func() { 88 c.sendHandshakeSeq-- 89 c.writeRecord(recordTypeHandshake, hs.finishedBytes) 90 c.flushHandshake() 91 }); err != nil { 92 return err 93 } 94 if err := hs.readFinished(nil, isResume); err != nil { 95 return err 96 } 97 c.didResume = true 98 } else { 99 // The client didn't include a session ticket, or it wasn't 100 // valid so we do a full handshake. 101 if err := hs.doFullHandshake(); err != nil { 102 return err 103 } 104 if err := hs.establishKeys(); err != nil { 105 return err 106 } 107 if err := hs.readFinished(c.firstFinished[:], isResume); err != nil { 108 return err 109 } 110 if c.config.Bugs.AlertBeforeFalseStartTest != 0 { 111 c.sendAlert(c.config.Bugs.AlertBeforeFalseStartTest) 112 } 113 if c.config.Bugs.ExpectFalseStart { 114 if err := c.readRecord(recordTypeApplicationData); err != nil { 115 return fmt.Errorf("tls: peer did not false start: %s", err) 116 } 117 } 118 if err := hs.sendSessionTicket(); err != nil { 119 return err 120 } 121 if err := hs.sendFinished(nil); err != nil { 122 return err 123 } 124 } 125 126 c.exporterSecret = hs.masterSecret 127 } 128 c.handshakeComplete = true 129 copy(c.clientRandom[:], hs.clientHello.random) 130 copy(c.serverRandom[:], hs.hello.random) 131 132 return nil 133} 134 135// readClientHello reads a ClientHello message from the client and determines 136// the protocol version. 137func (hs *serverHandshakeState) readClientHello() error { 138 config := hs.c.config 139 c := hs.c 140 141 if err := c.simulatePacketLoss(nil); err != nil { 142 return err 143 } 144 msg, err := c.readHandshake() 145 if err != nil { 146 return err 147 } 148 var ok bool 149 hs.clientHello, ok = msg.(*clientHelloMsg) 150 if !ok { 151 c.sendAlert(alertUnexpectedMessage) 152 return unexpectedMessageError(hs.clientHello, msg) 153 } 154 if size := config.Bugs.RequireClientHelloSize; size != 0 && len(hs.clientHello.raw) != size { 155 return fmt.Errorf("tls: ClientHello record size is %d, but expected %d", len(hs.clientHello.raw), size) 156 } 157 158 if c.isDTLS && !config.Bugs.SkipHelloVerifyRequest { 159 // Per RFC 6347, the version field in HelloVerifyRequest SHOULD 160 // be always DTLS 1.0 161 helloVerifyRequest := &helloVerifyRequestMsg{ 162 vers: versionToWire(VersionTLS10, c.isDTLS), 163 cookie: make([]byte, 32), 164 } 165 if _, err := io.ReadFull(c.config.rand(), helloVerifyRequest.cookie); err != nil { 166 c.sendAlert(alertInternalError) 167 return errors.New("dtls: short read from Rand: " + err.Error()) 168 } 169 c.writeRecord(recordTypeHandshake, helloVerifyRequest.marshal()) 170 c.flushHandshake() 171 172 if err := c.simulatePacketLoss(nil); err != nil { 173 return err 174 } 175 msg, err := c.readHandshake() 176 if err != nil { 177 return err 178 } 179 newClientHello, ok := msg.(*clientHelloMsg) 180 if !ok { 181 c.sendAlert(alertUnexpectedMessage) 182 return unexpectedMessageError(hs.clientHello, msg) 183 } 184 if !bytes.Equal(newClientHello.cookie, helloVerifyRequest.cookie) { 185 return errors.New("dtls: invalid cookie") 186 } 187 188 // Apart from the cookie, the two ClientHellos must 189 // match. Note that clientHello.equal compares the 190 // serialization, so we make a copy. 191 oldClientHelloCopy := *hs.clientHello 192 oldClientHelloCopy.raw = nil 193 oldClientHelloCopy.cookie = nil 194 newClientHelloCopy := *newClientHello 195 newClientHelloCopy.raw = nil 196 newClientHelloCopy.cookie = nil 197 if !oldClientHelloCopy.equal(&newClientHelloCopy) { 198 return errors.New("dtls: retransmitted ClientHello does not match") 199 } 200 hs.clientHello = newClientHello 201 } 202 203 if config.Bugs.RequireSameRenegoClientVersion && c.clientVersion != 0 { 204 if c.clientVersion != hs.clientHello.vers { 205 return fmt.Errorf("tls: client offered different version on renego") 206 } 207 } 208 209 c.clientVersion = hs.clientHello.vers 210 211 // Convert the ClientHello wire version to a protocol version. 212 var clientVersion uint16 213 if c.isDTLS { 214 if hs.clientHello.vers <= 0xfefd { 215 clientVersion = VersionTLS12 216 } else if hs.clientHello.vers <= 0xfeff { 217 clientVersion = VersionTLS10 218 } 219 } else { 220 if hs.clientHello.vers >= VersionTLS12 { 221 clientVersion = VersionTLS12 222 } else if hs.clientHello.vers >= VersionTLS11 { 223 clientVersion = VersionTLS11 224 } else if hs.clientHello.vers >= VersionTLS10 { 225 clientVersion = VersionTLS10 226 } else if hs.clientHello.vers >= VersionSSL30 { 227 clientVersion = VersionSSL30 228 } 229 } 230 231 if config.Bugs.NegotiateVersion != 0 { 232 c.vers = config.Bugs.NegotiateVersion 233 } else if c.haveVers && config.Bugs.NegotiateVersionOnRenego != 0 { 234 c.vers = config.Bugs.NegotiateVersionOnRenego 235 } else if len(hs.clientHello.supportedVersions) > 0 { 236 // Use the versions extension if supplied. 237 var foundVersion, foundGREASE bool 238 for _, extVersion := range hs.clientHello.supportedVersions { 239 if isGREASEValue(extVersion) { 240 foundGREASE = true 241 } 242 extVersion, ok = wireToVersion(extVersion, c.isDTLS) 243 if !ok { 244 continue 245 } 246 if config.isSupportedVersion(extVersion, c.isDTLS) && !foundVersion { 247 c.vers = extVersion 248 foundVersion = true 249 break 250 } 251 } 252 if !foundVersion { 253 c.sendAlert(alertProtocolVersion) 254 return errors.New("tls: client did not offer any supported protocol versions") 255 } 256 if config.Bugs.ExpectGREASE && !foundGREASE { 257 return errors.New("tls: no GREASE version value found") 258 } 259 } else { 260 // Otherwise, use the legacy ClientHello version. 261 version := clientVersion 262 if maxVersion := config.maxVersion(c.isDTLS); version > maxVersion { 263 version = maxVersion 264 } 265 if version == 0 || !config.isSupportedVersion(version, c.isDTLS) { 266 return fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers) 267 } 268 c.vers = version 269 } 270 c.haveVers = true 271 272 // Reject < 1.2 ClientHellos with signature_algorithms. 273 if clientVersion < VersionTLS12 && len(hs.clientHello.signatureAlgorithms) > 0 { 274 return fmt.Errorf("tls: client included signature_algorithms before TLS 1.2") 275 } 276 277 // Check the client cipher list is consistent with the version. 278 if clientVersion < VersionTLS12 { 279 for _, id := range hs.clientHello.cipherSuites { 280 if isTLS12Cipher(id) { 281 return fmt.Errorf("tls: client offered TLS 1.2 cipher before TLS 1.2") 282 } 283 } 284 } 285 286 if config.Bugs.ExpectNoTLS12Session { 287 if len(hs.clientHello.sessionId) > 0 { 288 return fmt.Errorf("tls: client offered an unexpected session ID") 289 } 290 if len(hs.clientHello.sessionTicket) > 0 { 291 return fmt.Errorf("tls: client offered an unexpected session ticket") 292 } 293 } 294 295 if config.Bugs.ExpectNoTLS13PSK && len(hs.clientHello.pskIdentities) > 0 { 296 return fmt.Errorf("tls: client offered unexpected PSK identities") 297 } 298 299 var scsvFound, greaseFound bool 300 for _, cipherSuite := range hs.clientHello.cipherSuites { 301 if cipherSuite == fallbackSCSV { 302 scsvFound = true 303 } 304 if isGREASEValue(cipherSuite) { 305 greaseFound = true 306 } 307 } 308 309 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV { 310 return errors.New("tls: no fallback SCSV found when expected") 311 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV { 312 return errors.New("tls: fallback SCSV found when not expected") 313 } 314 315 if !greaseFound && config.Bugs.ExpectGREASE { 316 return errors.New("tls: no GREASE cipher suite value found") 317 } 318 319 greaseFound = false 320 for _, curve := range hs.clientHello.supportedCurves { 321 if isGREASEValue(uint16(curve)) { 322 greaseFound = true 323 break 324 } 325 } 326 327 if !greaseFound && config.Bugs.ExpectGREASE { 328 return errors.New("tls: no GREASE curve value found") 329 } 330 331 if len(hs.clientHello.keyShares) > 0 { 332 greaseFound = false 333 for _, keyShare := range hs.clientHello.keyShares { 334 if isGREASEValue(uint16(keyShare.group)) { 335 greaseFound = true 336 break 337 } 338 } 339 340 if !greaseFound && config.Bugs.ExpectGREASE { 341 return errors.New("tls: no GREASE curve value found") 342 } 343 } 344 345 applyBugsToClientHello(hs.clientHello, config) 346 347 return nil 348} 349 350func applyBugsToClientHello(clientHello *clientHelloMsg, config *Config) { 351 if config.Bugs.IgnorePeerSignatureAlgorithmPreferences { 352 clientHello.signatureAlgorithms = config.signSignatureAlgorithms() 353 } 354 if config.Bugs.IgnorePeerCurvePreferences { 355 clientHello.supportedCurves = config.curvePreferences() 356 } 357 if config.Bugs.IgnorePeerCipherPreferences { 358 clientHello.cipherSuites = config.cipherSuites() 359 } 360} 361 362func (hs *serverHandshakeState) doTLS13Handshake() error { 363 c := hs.c 364 config := c.config 365 366 hs.hello = &serverHelloMsg{ 367 isDTLS: c.isDTLS, 368 vers: versionToWire(c.vers, c.isDTLS), 369 versOverride: config.Bugs.SendServerHelloVersion, 370 customExtension: config.Bugs.CustomUnencryptedExtension, 371 unencryptedALPN: config.Bugs.SendUnencryptedALPN, 372 } 373 374 hs.hello.random = make([]byte, 32) 375 if _, err := io.ReadFull(config.rand(), hs.hello.random); err != nil { 376 c.sendAlert(alertInternalError) 377 return err 378 } 379 380 // TLS 1.3 forbids clients from advertising any non-null compression. 381 if len(hs.clientHello.compressionMethods) != 1 || hs.clientHello.compressionMethods[0] != compressionNone { 382 return errors.New("tls: client sent compression method other than null for TLS 1.3") 383 } 384 385 // Prepare an EncryptedExtensions message, but do not send it yet. 386 encryptedExtensions := new(encryptedExtensionsMsg) 387 encryptedExtensions.empty = config.Bugs.EmptyEncryptedExtensions 388 if err := hs.processClientExtensions(&encryptedExtensions.extensions); err != nil { 389 return err 390 } 391 392 // Select the cipher suite. 393 var preferenceList, supportedList []uint16 394 if config.PreferServerCipherSuites { 395 preferenceList = config.cipherSuites() 396 supportedList = hs.clientHello.cipherSuites 397 } else { 398 preferenceList = hs.clientHello.cipherSuites 399 supportedList = config.cipherSuites() 400 } 401 402 for _, id := range preferenceList { 403 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, true, true); hs.suite != nil { 404 break 405 } 406 } 407 408 if hs.suite == nil { 409 c.sendAlert(alertHandshakeFailure) 410 return errors.New("tls: no cipher suite supported by both client and server") 411 } 412 413 hs.hello.cipherSuite = hs.suite.id 414 if c.config.Bugs.SendCipherSuite != 0 { 415 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite 416 } 417 418 hs.finishedHash = newFinishedHash(c.vers, hs.suite) 419 hs.finishedHash.discardHandshakeBuffer() 420 hs.writeClientHash(hs.clientHello.marshal()) 421 422 supportedCurve := false 423 var selectedCurve CurveID 424 preferredCurves := config.curvePreferences() 425Curves: 426 for _, curve := range hs.clientHello.supportedCurves { 427 for _, supported := range preferredCurves { 428 if supported == curve { 429 supportedCurve = true 430 selectedCurve = curve 431 break Curves 432 } 433 } 434 } 435 436 if !supportedCurve { 437 c.sendAlert(alertHandshakeFailure) 438 return errors.New("tls: no curve supported by both client and server") 439 } 440 441 pskIdentities := hs.clientHello.pskIdentities 442 pskKEModes := hs.clientHello.pskKEModes 443 444 if len(pskIdentities) == 0 && len(hs.clientHello.sessionTicket) > 0 && c.config.Bugs.AcceptAnySession { 445 psk := pskIdentity{ 446 ticket: hs.clientHello.sessionTicket, 447 } 448 pskIdentities = []pskIdentity{psk} 449 pskKEModes = []byte{pskDHEKEMode} 450 } 451 452 var pskIndex int 453 foundKEMode := bytes.IndexByte(pskKEModes, pskDHEKEMode) >= 0 454 if foundKEMode && !config.SessionTicketsDisabled { 455 for i, pskIdentity := range pskIdentities { 456 // TODO(svaldez): Check the obfuscatedTicketAge before accepting 0-RTT. 457 sessionState, ok := c.decryptTicket(pskIdentity.ticket) 458 if !ok { 459 continue 460 } 461 462 if !config.Bugs.AcceptAnySession { 463 if sessionState.vers != c.vers { 464 continue 465 } 466 if sessionState.ticketExpiration.Before(c.config.time()) { 467 continue 468 } 469 sessionCipher := cipherSuiteFromID(sessionState.cipherSuite) 470 if sessionCipher == nil || sessionCipher.hash() != hs.suite.hash() { 471 continue 472 } 473 } 474 475 clientTicketAge := time.Duration(uint32(pskIdentity.obfuscatedTicketAge-sessionState.ticketAgeAdd)) * time.Millisecond 476 if config.Bugs.ExpectTicketAge != 0 && clientTicketAge != config.Bugs.ExpectTicketAge { 477 c.sendAlert(alertHandshakeFailure) 478 return errors.New("tls: invalid ticket age") 479 } 480 481 hs.sessionState = sessionState 482 hs.hello.hasPSKIdentity = true 483 hs.hello.pskIdentity = uint16(i) 484 pskIndex = i 485 if config.Bugs.SelectPSKIdentityOnResume != 0 { 486 hs.hello.pskIdentity = config.Bugs.SelectPSKIdentityOnResume 487 } 488 c.didResume = true 489 break 490 } 491 } 492 493 if config.Bugs.AlwaysSelectPSKIdentity { 494 hs.hello.hasPSKIdentity = true 495 hs.hello.pskIdentity = 0 496 } 497 498 // Verify the PSK binder. Note there may not be a PSK binder if 499 // AcceptAnyBinder is set. See https://crbug.com/boringssl/115. 500 if hs.sessionState != nil && !config.Bugs.AcceptAnySession { 501 binderToVerify := hs.clientHello.pskBinders[pskIndex] 502 if err := verifyPSKBinder(hs.clientHello, hs.sessionState, binderToVerify, []byte{}); err != nil { 503 return err 504 } 505 } 506 507 // Resolve PSK and compute the early secret. 508 if hs.sessionState != nil { 509 hs.finishedHash.addEntropy(hs.sessionState.masterSecret) 510 } else { 511 hs.finishedHash.addEntropy(hs.finishedHash.zeroSecret()) 512 } 513 514 hs.hello.hasKeyShare = true 515 if hs.sessionState != nil && config.Bugs.NegotiatePSKResumption { 516 hs.hello.hasKeyShare = false 517 } 518 if config.Bugs.MissingKeyShare { 519 hs.hello.hasKeyShare = false 520 } 521 522 firstHelloRetryRequest := true 523 524ResendHelloRetryRequest: 525 var sendHelloRetryRequest bool 526 helloRetryRequest := &helloRetryRequestMsg{ 527 vers: versionToWire(c.vers, c.isDTLS), 528 duplicateExtensions: config.Bugs.DuplicateHelloRetryRequestExtensions, 529 } 530 531 if config.Bugs.AlwaysSendHelloRetryRequest { 532 sendHelloRetryRequest = true 533 } 534 535 if config.Bugs.SendHelloRetryRequestCookie != nil { 536 sendHelloRetryRequest = true 537 helloRetryRequest.cookie = config.Bugs.SendHelloRetryRequestCookie 538 } 539 540 if len(config.Bugs.CustomHelloRetryRequestExtension) > 0 { 541 sendHelloRetryRequest = true 542 helloRetryRequest.customExtension = config.Bugs.CustomHelloRetryRequestExtension 543 } 544 545 var selectedKeyShare *keyShareEntry 546 if hs.hello.hasKeyShare { 547 // Look for the key share corresponding to our selected curve. 548 for i := range hs.clientHello.keyShares { 549 if hs.clientHello.keyShares[i].group == selectedCurve { 550 selectedKeyShare = &hs.clientHello.keyShares[i] 551 break 552 } 553 } 554 555 if config.Bugs.ExpectMissingKeyShare && selectedKeyShare != nil { 556 return errors.New("tls: expected missing key share") 557 } 558 559 if selectedKeyShare == nil { 560 helloRetryRequest.hasSelectedGroup = true 561 helloRetryRequest.selectedGroup = selectedCurve 562 sendHelloRetryRequest = true 563 } 564 } 565 566 if config.Bugs.SendHelloRetryRequestCurve != 0 { 567 helloRetryRequest.hasSelectedGroup = true 568 helloRetryRequest.selectedGroup = config.Bugs.SendHelloRetryRequestCurve 569 sendHelloRetryRequest = true 570 } 571 572 if config.Bugs.SkipHelloRetryRequest { 573 sendHelloRetryRequest = false 574 } 575 576 if sendHelloRetryRequest { 577 oldClientHelloBytes := hs.clientHello.marshal() 578 hs.writeServerHash(helloRetryRequest.marshal()) 579 c.writeRecord(recordTypeHandshake, helloRetryRequest.marshal()) 580 c.flushHandshake() 581 582 if hs.clientHello.hasEarlyData { 583 c.skipEarlyData = true 584 } 585 586 // Read new ClientHello. 587 newMsg, err := c.readHandshake() 588 if err != nil { 589 return err 590 } 591 newClientHello, ok := newMsg.(*clientHelloMsg) 592 if !ok { 593 c.sendAlert(alertUnexpectedMessage) 594 return unexpectedMessageError(newClientHello, newMsg) 595 } 596 hs.writeClientHash(newClientHello.marshal()) 597 598 if newClientHello.hasEarlyData { 599 return errors.New("tls: EarlyData sent in new ClientHello") 600 } 601 602 applyBugsToClientHello(newClientHello, config) 603 604 // Check that the new ClientHello matches the old ClientHello, 605 // except for relevant modifications. 606 // 607 // TODO(davidben): Make this check more precise. 608 oldClientHelloCopy := *hs.clientHello 609 oldClientHelloCopy.raw = nil 610 oldClientHelloCopy.hasEarlyData = false 611 newClientHelloCopy := *newClientHello 612 newClientHelloCopy.raw = nil 613 614 if helloRetryRequest.hasSelectedGroup { 615 newKeyShares := newClientHelloCopy.keyShares 616 if len(newKeyShares) != 1 || newKeyShares[0].group != helloRetryRequest.selectedGroup { 617 return errors.New("tls: KeyShare from HelloRetryRequest not in new ClientHello") 618 } 619 selectedKeyShare = &newKeyShares[0] 620 newClientHelloCopy.keyShares = oldClientHelloCopy.keyShares 621 } 622 623 if len(helloRetryRequest.cookie) > 0 { 624 if !bytes.Equal(newClientHelloCopy.tls13Cookie, helloRetryRequest.cookie) { 625 return errors.New("tls: cookie from HelloRetryRequest not present in new ClientHello") 626 } 627 newClientHelloCopy.tls13Cookie = nil 628 } 629 630 // PSK binders and obfuscated ticket age are both updated in the 631 // second ClientHello. 632 if len(oldClientHelloCopy.pskIdentities) != len(newClientHelloCopy.pskIdentities) { 633 return errors.New("tls: PSK identity count from old and new ClientHello do not match") 634 } 635 for i, identity := range oldClientHelloCopy.pskIdentities { 636 newClientHelloCopy.pskIdentities[i].obfuscatedTicketAge = identity.obfuscatedTicketAge 637 } 638 newClientHelloCopy.pskBinders = oldClientHelloCopy.pskBinders 639 newClientHelloCopy.hasEarlyData = oldClientHelloCopy.hasEarlyData 640 641 if !oldClientHelloCopy.equal(&newClientHelloCopy) { 642 return errors.New("tls: new ClientHello does not match") 643 } 644 645 if firstHelloRetryRequest && config.Bugs.SecondHelloRetryRequest { 646 firstHelloRetryRequest = false 647 goto ResendHelloRetryRequest 648 } 649 650 // Verify the PSK binder. Note there may not be a PSK binder if 651 // AcceptAnyBinder is set. See https://crbug.com/115. 652 if hs.sessionState != nil && !config.Bugs.AcceptAnySession { 653 binderToVerify := newClientHello.pskBinders[pskIndex] 654 err := verifyPSKBinder(newClientHello, hs.sessionState, binderToVerify, append(oldClientHelloBytes, helloRetryRequest.marshal()...)) 655 if err != nil { 656 return err 657 } 658 } 659 } 660 661 // Decide whether or not to accept early data. 662 if !sendHelloRetryRequest && hs.clientHello.hasEarlyData { 663 if !config.Bugs.AlwaysRejectEarlyData && hs.sessionState != nil { 664 if c.clientProtocol == string(hs.sessionState.earlyALPN) || config.Bugs.AlwaysAcceptEarlyData { 665 encryptedExtensions.extensions.hasEarlyData = true 666 } 667 } 668 if encryptedExtensions.extensions.hasEarlyData { 669 earlyTrafficSecret := hs.finishedHash.deriveSecret(earlyTrafficLabel) 670 c.in.useTrafficSecret(c.vers, hs.suite, earlyTrafficSecret, clientWrite) 671 672 for _, expectedMsg := range config.Bugs.ExpectEarlyData { 673 if err := c.readRecord(recordTypeApplicationData); err != nil { 674 return err 675 } 676 if !bytes.Equal(c.input.data[c.input.off:], expectedMsg) { 677 return errors.New("ExpectEarlyData: did not get expected message") 678 } 679 c.in.freeBlock(c.input) 680 c.input = nil 681 682 } 683 } else { 684 c.skipEarlyData = true 685 } 686 } 687 688 if config.Bugs.SendEarlyDataExtension { 689 encryptedExtensions.extensions.hasEarlyData = true 690 } 691 692 // Resolve ECDHE and compute the handshake secret. 693 if hs.hello.hasKeyShare { 694 // Once a curve has been selected and a key share identified, 695 // the server needs to generate a public value and send it in 696 // the ServerHello. 697 curve, ok := curveForCurveID(selectedCurve) 698 if !ok { 699 panic("tls: server failed to look up curve ID") 700 } 701 c.curveID = selectedCurve 702 703 var peerKey []byte 704 if config.Bugs.SkipHelloRetryRequest { 705 // If skipping HelloRetryRequest, use a random key to 706 // avoid crashing. 707 curve2, _ := curveForCurveID(selectedCurve) 708 var err error 709 peerKey, err = curve2.offer(config.rand()) 710 if err != nil { 711 return err 712 } 713 } else { 714 peerKey = selectedKeyShare.keyExchange 715 } 716 717 publicKey, ecdheSecret, err := curve.accept(config.rand(), peerKey) 718 if err != nil { 719 c.sendAlert(alertHandshakeFailure) 720 return err 721 } 722 hs.finishedHash.addEntropy(ecdheSecret) 723 hs.hello.hasKeyShare = true 724 725 curveID := selectedCurve 726 if c.config.Bugs.SendCurve != 0 { 727 curveID = config.Bugs.SendCurve 728 } 729 if c.config.Bugs.InvalidECDHPoint { 730 publicKey[0] ^= 0xff 731 } 732 733 hs.hello.keyShare = keyShareEntry{ 734 group: curveID, 735 keyExchange: publicKey, 736 } 737 738 if config.Bugs.EncryptedExtensionsWithKeyShare { 739 encryptedExtensions.extensions.hasKeyShare = true 740 encryptedExtensions.extensions.keyShare = keyShareEntry{ 741 group: curveID, 742 keyExchange: publicKey, 743 } 744 } 745 } else { 746 hs.finishedHash.addEntropy(hs.finishedHash.zeroSecret()) 747 } 748 749 // Send unencrypted ServerHello. 750 hs.writeServerHash(hs.hello.marshal()) 751 if config.Bugs.PartialEncryptedExtensionsWithServerHello { 752 helloBytes := hs.hello.marshal() 753 toWrite := make([]byte, 0, len(helloBytes)+1) 754 toWrite = append(toWrite, helloBytes...) 755 toWrite = append(toWrite, typeEncryptedExtensions) 756 c.writeRecord(recordTypeHandshake, toWrite) 757 } else { 758 c.writeRecord(recordTypeHandshake, hs.hello.marshal()) 759 } 760 c.flushHandshake() 761 762 // Switch to handshake traffic keys. 763 serverHandshakeTrafficSecret := hs.finishedHash.deriveSecret(serverHandshakeTrafficLabel) 764 c.out.useTrafficSecret(c.vers, hs.suite, serverHandshakeTrafficSecret, serverWrite) 765 // Derive handshake traffic read key, but don't switch yet. 766 clientHandshakeTrafficSecret := hs.finishedHash.deriveSecret(clientHandshakeTrafficLabel) 767 768 // Send EncryptedExtensions. 769 hs.writeServerHash(encryptedExtensions.marshal()) 770 if config.Bugs.PartialEncryptedExtensionsWithServerHello { 771 // The first byte has already been sent. 772 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()[1:]) 773 } else { 774 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()) 775 } 776 777 if hs.sessionState == nil { 778 if config.ClientAuth >= RequestClientCert { 779 // Request a client certificate 780 certReq := &certificateRequestMsg{ 781 hasSignatureAlgorithm: true, 782 hasRequestContext: true, 783 requestContext: config.Bugs.SendRequestContext, 784 } 785 if !config.Bugs.NoSignatureAlgorithms { 786 certReq.signatureAlgorithms = config.verifySignatureAlgorithms() 787 } 788 789 // An empty list of certificateAuthorities signals to 790 // the client that it may send any certificate in response 791 // to our request. When we know the CAs we trust, then 792 // we can send them down, so that the client can choose 793 // an appropriate certificate to give to us. 794 if config.ClientCAs != nil { 795 certReq.certificateAuthorities = config.ClientCAs.Subjects() 796 } 797 hs.writeServerHash(certReq.marshal()) 798 c.writeRecord(recordTypeHandshake, certReq.marshal()) 799 } 800 801 certMsg := &certificateMsg{ 802 hasRequestContext: true, 803 } 804 if !config.Bugs.EmptyCertificateList { 805 for i, certData := range hs.cert.Certificate { 806 cert := certificateEntry{ 807 data: certData, 808 } 809 if i == 0 { 810 if hs.clientHello.ocspStapling { 811 cert.ocspResponse = hs.cert.OCSPStaple 812 } 813 if hs.clientHello.sctListSupported { 814 cert.sctList = hs.cert.SignedCertificateTimestampList 815 } 816 cert.duplicateExtensions = config.Bugs.SendDuplicateCertExtensions 817 cert.extraExtension = config.Bugs.SendExtensionOnCertificate 818 } else { 819 if config.Bugs.SendOCSPOnIntermediates != nil { 820 cert.ocspResponse = config.Bugs.SendOCSPOnIntermediates 821 } 822 if config.Bugs.SendSCTOnIntermediates != nil { 823 cert.sctList = config.Bugs.SendSCTOnIntermediates 824 } 825 } 826 certMsg.certificates = append(certMsg.certificates, cert) 827 } 828 } 829 certMsgBytes := certMsg.marshal() 830 hs.writeServerHash(certMsgBytes) 831 c.writeRecord(recordTypeHandshake, certMsgBytes) 832 833 certVerify := &certificateVerifyMsg{ 834 hasSignatureAlgorithm: true, 835 } 836 837 // Determine the hash to sign. 838 privKey := hs.cert.PrivateKey 839 840 var err error 841 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, config, hs.clientHello.signatureAlgorithms) 842 if err != nil { 843 c.sendAlert(alertInternalError) 844 return err 845 } 846 847 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13) 848 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input) 849 if err != nil { 850 c.sendAlert(alertInternalError) 851 return err 852 } 853 854 if config.Bugs.SendSignatureAlgorithm != 0 { 855 certVerify.signatureAlgorithm = config.Bugs.SendSignatureAlgorithm 856 } 857 858 hs.writeServerHash(certVerify.marshal()) 859 c.writeRecord(recordTypeHandshake, certVerify.marshal()) 860 } else if hs.sessionState != nil { 861 // Pick up certificates from the session instead. 862 if len(hs.sessionState.certificates) > 0 { 863 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil { 864 return err 865 } 866 } 867 } 868 869 finished := new(finishedMsg) 870 finished.verifyData = hs.finishedHash.serverSum(serverHandshakeTrafficSecret) 871 if config.Bugs.BadFinished { 872 finished.verifyData[0]++ 873 } 874 hs.writeServerHash(finished.marshal()) 875 c.writeRecord(recordTypeHandshake, finished.marshal()) 876 if c.config.Bugs.SendExtraFinished { 877 c.writeRecord(recordTypeHandshake, finished.marshal()) 878 } 879 c.flushHandshake() 880 881 // The various secrets do not incorporate the client's final leg, so 882 // derive them now before updating the handshake context. 883 hs.finishedHash.addEntropy(hs.finishedHash.zeroSecret()) 884 clientTrafficSecret := hs.finishedHash.deriveSecret(clientApplicationTrafficLabel) 885 serverTrafficSecret := hs.finishedHash.deriveSecret(serverApplicationTrafficLabel) 886 c.exporterSecret = hs.finishedHash.deriveSecret(exporterLabel) 887 888 // Switch to application data keys on write. In particular, any alerts 889 // from the client certificate are sent over these keys. 890 c.out.useTrafficSecret(c.vers, hs.suite, serverTrafficSecret, serverWrite) 891 892 // Send 0.5-RTT messages. 893 for _, halfRTTMsg := range config.Bugs.SendHalfRTTData { 894 if _, err := c.writeRecord(recordTypeApplicationData, halfRTTMsg); err != nil { 895 return err 896 } 897 } 898 899 // Read end_of_early_data alert. 900 if encryptedExtensions.extensions.hasEarlyData { 901 if err := c.readRecord(recordTypeAlert); err != errEndOfEarlyDataAlert { 902 if err == nil { 903 panic("readRecord(recordTypeAlert) returned nil") 904 } 905 return err 906 } 907 } 908 909 // Switch input stream to handshake traffic keys. 910 c.in.useTrafficSecret(c.vers, hs.suite, clientHandshakeTrafficSecret, clientWrite) 911 912 // If we requested a client certificate, then the client must send a 913 // certificate message, even if it's empty. 914 if config.ClientAuth >= RequestClientCert { 915 msg, err := c.readHandshake() 916 if err != nil { 917 return err 918 } 919 920 certMsg, ok := msg.(*certificateMsg) 921 if !ok { 922 c.sendAlert(alertUnexpectedMessage) 923 return unexpectedMessageError(certMsg, msg) 924 } 925 hs.writeClientHash(certMsg.marshal()) 926 927 if len(certMsg.certificates) == 0 { 928 // The client didn't actually send a certificate 929 switch config.ClientAuth { 930 case RequireAnyClientCert, RequireAndVerifyClientCert: 931 c.sendAlert(alertCertificateRequired) 932 return errors.New("tls: client didn't provide a certificate") 933 } 934 } 935 936 var certs [][]byte 937 for _, cert := range certMsg.certificates { 938 certs = append(certs, cert.data) 939 // OCSP responses and SCT lists are not negotiated in 940 // client certificates. 941 if cert.ocspResponse != nil || cert.sctList != nil { 942 c.sendAlert(alertUnsupportedExtension) 943 return errors.New("tls: unexpected extensions in the client certificate") 944 } 945 } 946 pub, err := hs.processCertsFromClient(certs) 947 if err != nil { 948 return err 949 } 950 951 if len(c.peerCertificates) > 0 { 952 msg, err = c.readHandshake() 953 if err != nil { 954 return err 955 } 956 957 certVerify, ok := msg.(*certificateVerifyMsg) 958 if !ok { 959 c.sendAlert(alertUnexpectedMessage) 960 return unexpectedMessageError(certVerify, msg) 961 } 962 963 c.peerSignatureAlgorithm = certVerify.signatureAlgorithm 964 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13) 965 if err := verifyMessage(c.vers, pub, config, certVerify.signatureAlgorithm, input, certVerify.signature); err != nil { 966 c.sendAlert(alertBadCertificate) 967 return err 968 } 969 hs.writeClientHash(certVerify.marshal()) 970 } 971 } 972 973 if encryptedExtensions.extensions.channelIDRequested { 974 msg, err := c.readHandshake() 975 if err != nil { 976 return err 977 } 978 channelIDMsg, ok := msg.(*channelIDMsg) 979 if !ok { 980 c.sendAlert(alertUnexpectedMessage) 981 return unexpectedMessageError(channelIDMsg, msg) 982 } 983 channelIDHash := crypto.SHA256.New() 984 channelIDHash.Write(hs.finishedHash.certificateVerifyInput(channelIDContextTLS13)) 985 channelID, err := verifyChannelIDMessage(channelIDMsg, channelIDHash.Sum(nil)) 986 if err != nil { 987 return err 988 } 989 c.channelID = channelID 990 991 hs.writeClientHash(channelIDMsg.marshal()) 992 } 993 994 // Read the client Finished message. 995 msg, err := c.readHandshake() 996 if err != nil { 997 return err 998 } 999 clientFinished, ok := msg.(*finishedMsg) 1000 if !ok { 1001 c.sendAlert(alertUnexpectedMessage) 1002 return unexpectedMessageError(clientFinished, msg) 1003 } 1004 1005 verify := hs.finishedHash.clientSum(clientHandshakeTrafficSecret) 1006 if len(verify) != len(clientFinished.verifyData) || 1007 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 { 1008 c.sendAlert(alertHandshakeFailure) 1009 return errors.New("tls: client's Finished message was incorrect") 1010 } 1011 hs.writeClientHash(clientFinished.marshal()) 1012 1013 // Switch to application data keys on read. 1014 c.in.useTrafficSecret(c.vers, hs.suite, clientTrafficSecret, clientWrite) 1015 1016 c.cipherSuite = hs.suite 1017 c.resumptionSecret = hs.finishedHash.deriveSecret(resumptionLabel) 1018 1019 // TODO(davidben): Allow configuring the number of tickets sent for 1020 // testing. 1021 if !c.config.SessionTicketsDisabled && foundKEMode { 1022 ticketCount := 2 1023 for i := 0; i < ticketCount; i++ { 1024 c.SendNewSessionTicket() 1025 } 1026 } 1027 return nil 1028} 1029 1030// processClientHello processes the ClientHello message from the client and 1031// decides whether we will perform session resumption. 1032func (hs *serverHandshakeState) processClientHello() (isResume bool, err error) { 1033 config := hs.c.config 1034 c := hs.c 1035 1036 hs.hello = &serverHelloMsg{ 1037 isDTLS: c.isDTLS, 1038 vers: versionToWire(c.vers, c.isDTLS), 1039 versOverride: config.Bugs.SendServerHelloVersion, 1040 compressionMethod: compressionNone, 1041 } 1042 1043 hs.hello.random = make([]byte, 32) 1044 _, err = io.ReadFull(config.rand(), hs.hello.random) 1045 if err != nil { 1046 c.sendAlert(alertInternalError) 1047 return false, err 1048 } 1049 // Signal downgrades in the server random, per draft-ietf-tls-tls13-16, 1050 // section 4.1.3. 1051 if c.vers <= VersionTLS12 && config.maxVersion(c.isDTLS) >= VersionTLS13 { 1052 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS13) 1053 } 1054 if c.vers <= VersionTLS11 && config.maxVersion(c.isDTLS) == VersionTLS12 { 1055 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS12) 1056 } 1057 1058 foundCompression := false 1059 // We only support null compression, so check that the client offered it. 1060 for _, compression := range hs.clientHello.compressionMethods { 1061 if compression == compressionNone { 1062 foundCompression = true 1063 break 1064 } 1065 } 1066 1067 if !foundCompression { 1068 c.sendAlert(alertHandshakeFailure) 1069 return false, errors.New("tls: client does not support uncompressed connections") 1070 } 1071 1072 if err := hs.processClientExtensions(&hs.hello.extensions); err != nil { 1073 return false, err 1074 } 1075 1076 supportedCurve := false 1077 preferredCurves := config.curvePreferences() 1078Curves: 1079 for _, curve := range hs.clientHello.supportedCurves { 1080 for _, supported := range preferredCurves { 1081 if supported == curve { 1082 supportedCurve = true 1083 break Curves 1084 } 1085 } 1086 } 1087 1088 supportedPointFormat := false 1089 for _, pointFormat := range hs.clientHello.supportedPoints { 1090 if pointFormat == pointFormatUncompressed { 1091 supportedPointFormat = true 1092 break 1093 } 1094 } 1095 hs.ellipticOk = supportedCurve && supportedPointFormat 1096 1097 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey) 1098 1099 // For test purposes, check that the peer never offers a session when 1100 // renegotiating. 1101 if c.cipherSuite != nil && len(hs.clientHello.sessionId) > 0 && c.config.Bugs.FailIfResumeOnRenego { 1102 return false, errors.New("tls: offered resumption on renegotiation") 1103 } 1104 1105 if c.config.Bugs.FailIfSessionOffered && (len(hs.clientHello.sessionTicket) > 0 || len(hs.clientHello.sessionId) > 0) { 1106 return false, errors.New("tls: client offered a session ticket or ID") 1107 } 1108 1109 if hs.checkForResumption() { 1110 return true, nil 1111 } 1112 1113 var preferenceList, supportedList []uint16 1114 if c.config.PreferServerCipherSuites { 1115 preferenceList = c.config.cipherSuites() 1116 supportedList = hs.clientHello.cipherSuites 1117 } else { 1118 preferenceList = hs.clientHello.cipherSuites 1119 supportedList = c.config.cipherSuites() 1120 } 1121 1122 for _, id := range preferenceList { 1123 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil { 1124 break 1125 } 1126 } 1127 1128 if hs.suite == nil { 1129 c.sendAlert(alertHandshakeFailure) 1130 return false, errors.New("tls: no cipher suite supported by both client and server") 1131 } 1132 1133 return false, nil 1134} 1135 1136// processClientExtensions processes all ClientHello extensions not directly 1137// related to cipher suite negotiation and writes responses in serverExtensions. 1138func (hs *serverHandshakeState) processClientExtensions(serverExtensions *serverExtensions) error { 1139 config := hs.c.config 1140 c := hs.c 1141 1142 if c.vers < VersionTLS13 || config.Bugs.NegotiateRenegotiationInfoAtAllVersions { 1143 if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) { 1144 c.sendAlert(alertHandshakeFailure) 1145 return errors.New("tls: renegotiation mismatch") 1146 } 1147 1148 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo { 1149 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.clientVerify...) 1150 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.serverVerify...) 1151 if c.config.Bugs.BadRenegotiationInfo { 1152 serverExtensions.secureRenegotiation[0] ^= 0x80 1153 } 1154 } else { 1155 serverExtensions.secureRenegotiation = hs.clientHello.secureRenegotiation 1156 } 1157 1158 if c.noRenegotiationInfo() { 1159 serverExtensions.secureRenegotiation = nil 1160 } 1161 } 1162 1163 serverExtensions.duplicateExtension = c.config.Bugs.DuplicateExtension 1164 1165 if len(hs.clientHello.serverName) > 0 { 1166 c.serverName = hs.clientHello.serverName 1167 } 1168 if len(config.Certificates) == 0 { 1169 c.sendAlert(alertInternalError) 1170 return errors.New("tls: no certificates configured") 1171 } 1172 hs.cert = &config.Certificates[0] 1173 if len(hs.clientHello.serverName) > 0 { 1174 hs.cert = config.getCertificateForName(hs.clientHello.serverName) 1175 } 1176 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName { 1177 return errors.New("tls: unexpected server name") 1178 } 1179 1180 if cert := config.Bugs.RenegotiationCertificate; c.cipherSuite != nil && cert != nil { 1181 hs.cert = cert 1182 } 1183 1184 if len(hs.clientHello.alpnProtocols) > 0 { 1185 // We will never offer ALPN as a client on renegotiation 1186 // handshakes. 1187 if len(c.clientVerify) > 0 { 1188 return errors.New("tls: offered ALPN on renegotiation") 1189 } 1190 if proto := c.config.Bugs.ALPNProtocol; proto != nil { 1191 serverExtensions.alpnProtocol = *proto 1192 serverExtensions.alpnProtocolEmpty = len(*proto) == 0 1193 c.clientProtocol = *proto 1194 c.usedALPN = true 1195 } else if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback { 1196 serverExtensions.alpnProtocol = selectedProto 1197 c.clientProtocol = selectedProto 1198 c.usedALPN = true 1199 } 1200 } 1201 1202 if len(c.config.Bugs.SendALPN) > 0 { 1203 serverExtensions.alpnProtocol = c.config.Bugs.SendALPN 1204 } 1205 1206 if c.vers < VersionTLS13 || config.Bugs.NegotiateNPNAtAllVersions { 1207 if len(hs.clientHello.alpnProtocols) == 0 || c.config.Bugs.NegotiateALPNAndNPN { 1208 // Although sending an empty NPN extension is reasonable, Firefox has 1209 // had a bug around this. Best to send nothing at all if 1210 // config.NextProtos is empty. See 1211 // https://code.google.com/p/go/issues/detail?id=5445. 1212 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 { 1213 serverExtensions.nextProtoNeg = true 1214 serverExtensions.nextProtos = config.NextProtos 1215 serverExtensions.npnAfterAlpn = config.Bugs.SwapNPNAndALPN 1216 } 1217 } 1218 } 1219 1220 if c.vers < VersionTLS13 || config.Bugs.NegotiateEMSAtAllVersions { 1221 disableEMS := config.Bugs.NoExtendedMasterSecret 1222 if c.cipherSuite != nil { 1223 disableEMS = config.Bugs.NoExtendedMasterSecretOnRenegotiation 1224 } 1225 serverExtensions.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !disableEMS 1226 } 1227 1228 if hs.clientHello.channelIDSupported && config.RequestChannelID { 1229 serverExtensions.channelIDRequested = true 1230 } 1231 1232 if hs.clientHello.srtpProtectionProfiles != nil { 1233 SRTPLoop: 1234 for _, p1 := range c.config.SRTPProtectionProfiles { 1235 for _, p2 := range hs.clientHello.srtpProtectionProfiles { 1236 if p1 == p2 { 1237 serverExtensions.srtpProtectionProfile = p1 1238 c.srtpProtectionProfile = p1 1239 break SRTPLoop 1240 } 1241 } 1242 } 1243 } 1244 1245 if c.config.Bugs.SendSRTPProtectionProfile != 0 { 1246 serverExtensions.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile 1247 } 1248 1249 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil { 1250 if hs.clientHello.customExtension != *expected { 1251 return fmt.Errorf("tls: bad custom extension contents %q", hs.clientHello.customExtension) 1252 } 1253 } 1254 serverExtensions.customExtension = config.Bugs.CustomExtension 1255 1256 if c.config.Bugs.AdvertiseTicketExtension { 1257 serverExtensions.ticketSupported = true 1258 } 1259 1260 if c.config.Bugs.SendSupportedPointFormats != nil { 1261 serverExtensions.supportedPoints = c.config.Bugs.SendSupportedPointFormats 1262 } 1263 1264 if !hs.clientHello.hasGREASEExtension && config.Bugs.ExpectGREASE { 1265 return errors.New("tls: no GREASE extension found") 1266 } 1267 1268 serverExtensions.serverNameAck = c.config.Bugs.SendServerNameAck 1269 1270 return nil 1271} 1272 1273// checkForResumption returns true if we should perform resumption on this connection. 1274func (hs *serverHandshakeState) checkForResumption() bool { 1275 c := hs.c 1276 1277 ticket := hs.clientHello.sessionTicket 1278 if len(ticket) == 0 && len(hs.clientHello.pskIdentities) > 0 && c.config.Bugs.AcceptAnySession { 1279 ticket = hs.clientHello.pskIdentities[0].ticket 1280 } 1281 if len(ticket) > 0 { 1282 if c.config.SessionTicketsDisabled { 1283 return false 1284 } 1285 1286 var ok bool 1287 if hs.sessionState, ok = c.decryptTicket(ticket); !ok { 1288 return false 1289 } 1290 } else { 1291 if c.config.ServerSessionCache == nil { 1292 return false 1293 } 1294 1295 var ok bool 1296 sessionId := string(hs.clientHello.sessionId) 1297 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok { 1298 return false 1299 } 1300 } 1301 1302 if c.config.Bugs.AcceptAnySession { 1303 // Replace the cipher suite with one known to work, to test 1304 // cross-version resumption attempts. 1305 hs.sessionState.cipherSuite = TLS_RSA_WITH_AES_128_CBC_SHA 1306 } else { 1307 // Never resume a session for a different SSL version. 1308 if c.vers != hs.sessionState.vers { 1309 return false 1310 } 1311 1312 cipherSuiteOk := false 1313 // Check that the client is still offering the ciphersuite in the session. 1314 for _, id := range hs.clientHello.cipherSuites { 1315 if id == hs.sessionState.cipherSuite { 1316 cipherSuiteOk = true 1317 break 1318 } 1319 } 1320 if !cipherSuiteOk { 1321 return false 1322 } 1323 } 1324 1325 // Check that we also support the ciphersuite from the session. 1326 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), c.vers, hs.ellipticOk, hs.ecdsaOk) 1327 1328 if hs.suite == nil { 1329 return false 1330 } 1331 1332 sessionHasClientCerts := len(hs.sessionState.certificates) != 0 1333 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert 1334 if needClientCerts && !sessionHasClientCerts { 1335 return false 1336 } 1337 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert { 1338 return false 1339 } 1340 1341 return true 1342} 1343 1344func (hs *serverHandshakeState) doResumeHandshake() error { 1345 c := hs.c 1346 1347 hs.hello.cipherSuite = hs.suite.id 1348 if c.config.Bugs.SendCipherSuite != 0 { 1349 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite 1350 } 1351 // We echo the client's session ID in the ServerHello to let it know 1352 // that we're doing a resumption. 1353 hs.hello.sessionId = hs.clientHello.sessionId 1354 hs.hello.extensions.ticketSupported = c.config.Bugs.RenewTicketOnResume 1355 1356 if c.config.Bugs.SendSCTListOnResume != nil { 1357 hs.hello.extensions.sctList = c.config.Bugs.SendSCTListOnResume 1358 } 1359 1360 if c.config.Bugs.SendOCSPResponseOnResume != nil { 1361 // There is no way, syntactically, to send an OCSP response on a 1362 // resumption handshake. 1363 hs.hello.extensions.ocspStapling = true 1364 } 1365 1366 hs.finishedHash = newFinishedHash(c.vers, hs.suite) 1367 hs.finishedHash.discardHandshakeBuffer() 1368 hs.writeClientHash(hs.clientHello.marshal()) 1369 hs.writeServerHash(hs.hello.marshal()) 1370 1371 c.writeRecord(recordTypeHandshake, hs.hello.marshal()) 1372 1373 if len(hs.sessionState.certificates) > 0 { 1374 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil { 1375 return err 1376 } 1377 } 1378 1379 hs.masterSecret = hs.sessionState.masterSecret 1380 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret 1381 1382 return nil 1383} 1384 1385func (hs *serverHandshakeState) doFullHandshake() error { 1386 config := hs.c.config 1387 c := hs.c 1388 1389 isPSK := hs.suite.flags&suitePSK != 0 1390 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 { 1391 hs.hello.extensions.ocspStapling = true 1392 } 1393 1394 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 { 1395 hs.hello.extensions.sctList = hs.cert.SignedCertificateTimestampList 1396 } 1397 1398 hs.hello.extensions.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30 1399 hs.hello.cipherSuite = hs.suite.id 1400 if config.Bugs.SendCipherSuite != 0 { 1401 hs.hello.cipherSuite = config.Bugs.SendCipherSuite 1402 } 1403 c.extendedMasterSecret = hs.hello.extensions.extendedMasterSecret 1404 1405 // Generate a session ID if we're to save the session. 1406 if !hs.hello.extensions.ticketSupported && config.ServerSessionCache != nil { 1407 hs.hello.sessionId = make([]byte, 32) 1408 if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil { 1409 c.sendAlert(alertInternalError) 1410 return errors.New("tls: short read from Rand: " + err.Error()) 1411 } 1412 } 1413 1414 hs.finishedHash = newFinishedHash(c.vers, hs.suite) 1415 hs.writeClientHash(hs.clientHello.marshal()) 1416 hs.writeServerHash(hs.hello.marshal()) 1417 1418 if config.Bugs.SendSNIWarningAlert { 1419 c.SendAlert(alertLevelWarning, alertUnrecognizedName) 1420 } 1421 1422 c.writeRecord(recordTypeHandshake, hs.hello.marshal()) 1423 1424 if !isPSK { 1425 certMsg := new(certificateMsg) 1426 if !config.Bugs.EmptyCertificateList { 1427 for _, certData := range hs.cert.Certificate { 1428 certMsg.certificates = append(certMsg.certificates, certificateEntry{ 1429 data: certData, 1430 }) 1431 } 1432 } 1433 if !config.Bugs.UnauthenticatedECDH { 1434 certMsgBytes := certMsg.marshal() 1435 hs.writeServerHash(certMsgBytes) 1436 c.writeRecord(recordTypeHandshake, certMsgBytes) 1437 } 1438 } 1439 1440 if hs.hello.extensions.ocspStapling && !c.config.Bugs.SkipCertificateStatus { 1441 certStatus := new(certificateStatusMsg) 1442 certStatus.statusType = statusTypeOCSP 1443 certStatus.response = hs.cert.OCSPStaple 1444 hs.writeServerHash(certStatus.marshal()) 1445 c.writeRecord(recordTypeHandshake, certStatus.marshal()) 1446 } 1447 1448 keyAgreement := hs.suite.ka(c.vers) 1449 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello) 1450 if err != nil { 1451 c.sendAlert(alertHandshakeFailure) 1452 return err 1453 } 1454 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok { 1455 c.curveID = ecdhe.curveID 1456 } 1457 if skx != nil && !config.Bugs.SkipServerKeyExchange { 1458 hs.writeServerHash(skx.marshal()) 1459 c.writeRecord(recordTypeHandshake, skx.marshal()) 1460 } 1461 1462 if config.ClientAuth >= RequestClientCert { 1463 // Request a client certificate 1464 certReq := &certificateRequestMsg{ 1465 certificateTypes: config.ClientCertificateTypes, 1466 } 1467 if certReq.certificateTypes == nil { 1468 certReq.certificateTypes = []byte{ 1469 byte(CertTypeRSASign), 1470 byte(CertTypeECDSASign), 1471 } 1472 } 1473 if c.vers >= VersionTLS12 { 1474 certReq.hasSignatureAlgorithm = true 1475 if !config.Bugs.NoSignatureAlgorithms { 1476 certReq.signatureAlgorithms = config.verifySignatureAlgorithms() 1477 } 1478 } 1479 1480 // An empty list of certificateAuthorities signals to 1481 // the client that it may send any certificate in response 1482 // to our request. When we know the CAs we trust, then 1483 // we can send them down, so that the client can choose 1484 // an appropriate certificate to give to us. 1485 if config.ClientCAs != nil { 1486 certReq.certificateAuthorities = config.ClientCAs.Subjects() 1487 } 1488 hs.writeServerHash(certReq.marshal()) 1489 c.writeRecord(recordTypeHandshake, certReq.marshal()) 1490 } 1491 1492 helloDone := new(serverHelloDoneMsg) 1493 hs.writeServerHash(helloDone.marshal()) 1494 c.writeRecord(recordTypeHandshake, helloDone.marshal()) 1495 c.flushHandshake() 1496 1497 var pub crypto.PublicKey // public key for client auth, if any 1498 1499 if err := c.simulatePacketLoss(nil); err != nil { 1500 return err 1501 } 1502 msg, err := c.readHandshake() 1503 if err != nil { 1504 return err 1505 } 1506 1507 var ok bool 1508 // If we requested a client certificate, then the client must send a 1509 // certificate message, even if it's empty. 1510 if config.ClientAuth >= RequestClientCert { 1511 var certMsg *certificateMsg 1512 var certificates [][]byte 1513 if certMsg, ok = msg.(*certificateMsg); ok { 1514 if c.vers == VersionSSL30 && len(certMsg.certificates) == 0 { 1515 return errors.New("tls: empty certificate message in SSL 3.0") 1516 } 1517 1518 hs.writeClientHash(certMsg.marshal()) 1519 for _, cert := range certMsg.certificates { 1520 certificates = append(certificates, cert.data) 1521 } 1522 } else if c.vers == VersionSSL30 { 1523 // In SSL 3.0, no certificate is signaled by a warning 1524 // alert which we translate to ssl3NoCertificateMsg. 1525 if _, ok := msg.(*ssl3NoCertificateMsg); !ok { 1526 return errors.New("tls: client provided neither a certificate nor no_certificate warning alert") 1527 } 1528 } else { 1529 // In TLS, the Certificate message is required. In SSL 1530 // 3.0, the peer skips it when sending no certificates. 1531 c.sendAlert(alertUnexpectedMessage) 1532 return unexpectedMessageError(certMsg, msg) 1533 } 1534 1535 if len(certificates) == 0 { 1536 // The client didn't actually send a certificate 1537 switch config.ClientAuth { 1538 case RequireAnyClientCert, RequireAndVerifyClientCert: 1539 c.sendAlert(alertBadCertificate) 1540 return errors.New("tls: client didn't provide a certificate") 1541 } 1542 } 1543 1544 pub, err = hs.processCertsFromClient(certificates) 1545 if err != nil { 1546 return err 1547 } 1548 1549 msg, err = c.readHandshake() 1550 if err != nil { 1551 return err 1552 } 1553 } 1554 1555 // Get client key exchange 1556 ckx, ok := msg.(*clientKeyExchangeMsg) 1557 if !ok { 1558 c.sendAlert(alertUnexpectedMessage) 1559 return unexpectedMessageError(ckx, msg) 1560 } 1561 hs.writeClientHash(ckx.marshal()) 1562 1563 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers) 1564 if err != nil { 1565 c.sendAlert(alertHandshakeFailure) 1566 return err 1567 } 1568 if c.extendedMasterSecret { 1569 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash) 1570 } else { 1571 if c.config.Bugs.RequireExtendedMasterSecret { 1572 return errors.New("tls: extended master secret required but not supported by peer") 1573 } 1574 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random) 1575 } 1576 1577 // If we received a client cert in response to our certificate request message, 1578 // the client will send us a certificateVerifyMsg immediately after the 1579 // clientKeyExchangeMsg. This message is a digest of all preceding 1580 // handshake-layer messages that is signed using the private key corresponding 1581 // to the client's certificate. This allows us to verify that the client is in 1582 // possession of the private key of the certificate. 1583 if len(c.peerCertificates) > 0 { 1584 msg, err = c.readHandshake() 1585 if err != nil { 1586 return err 1587 } 1588 certVerify, ok := msg.(*certificateVerifyMsg) 1589 if !ok { 1590 c.sendAlert(alertUnexpectedMessage) 1591 return unexpectedMessageError(certVerify, msg) 1592 } 1593 1594 // Determine the signature type. 1595 var sigAlg signatureAlgorithm 1596 if certVerify.hasSignatureAlgorithm { 1597 sigAlg = certVerify.signatureAlgorithm 1598 c.peerSignatureAlgorithm = sigAlg 1599 } 1600 1601 if c.vers > VersionSSL30 { 1602 err = verifyMessage(c.vers, pub, c.config, sigAlg, hs.finishedHash.buffer, certVerify.signature) 1603 } else { 1604 // SSL 3.0's client certificate construction is 1605 // incompatible with signatureAlgorithm. 1606 rsaPub, ok := pub.(*rsa.PublicKey) 1607 if !ok { 1608 err = errors.New("unsupported key type for client certificate") 1609 } else { 1610 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret) 1611 err = rsa.VerifyPKCS1v15(rsaPub, crypto.MD5SHA1, digest, certVerify.signature) 1612 } 1613 } 1614 if err != nil { 1615 c.sendAlert(alertBadCertificate) 1616 return errors.New("could not validate signature of connection nonces: " + err.Error()) 1617 } 1618 1619 hs.writeClientHash(certVerify.marshal()) 1620 } 1621 1622 hs.finishedHash.discardHandshakeBuffer() 1623 1624 return nil 1625} 1626 1627func (hs *serverHandshakeState) establishKeys() error { 1628 c := hs.c 1629 1630 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV := 1631 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen(c.vers)) 1632 1633 var clientCipher, serverCipher interface{} 1634 var clientHash, serverHash macFunction 1635 1636 if hs.suite.aead == nil { 1637 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */) 1638 clientHash = hs.suite.mac(c.vers, clientMAC) 1639 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */) 1640 serverHash = hs.suite.mac(c.vers, serverMAC) 1641 } else { 1642 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV) 1643 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV) 1644 } 1645 1646 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash) 1647 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash) 1648 1649 return nil 1650} 1651 1652func (hs *serverHandshakeState) readFinished(out []byte, isResume bool) error { 1653 c := hs.c 1654 1655 c.readRecord(recordTypeChangeCipherSpec) 1656 if err := c.in.error(); err != nil { 1657 return err 1658 } 1659 1660 if hs.hello.extensions.nextProtoNeg { 1661 msg, err := c.readHandshake() 1662 if err != nil { 1663 return err 1664 } 1665 nextProto, ok := msg.(*nextProtoMsg) 1666 if !ok { 1667 c.sendAlert(alertUnexpectedMessage) 1668 return unexpectedMessageError(nextProto, msg) 1669 } 1670 hs.writeClientHash(nextProto.marshal()) 1671 c.clientProtocol = nextProto.proto 1672 } 1673 1674 if hs.hello.extensions.channelIDRequested { 1675 msg, err := c.readHandshake() 1676 if err != nil { 1677 return err 1678 } 1679 channelIDMsg, ok := msg.(*channelIDMsg) 1680 if !ok { 1681 c.sendAlert(alertUnexpectedMessage) 1682 return unexpectedMessageError(channelIDMsg, msg) 1683 } 1684 var resumeHash []byte 1685 if isResume { 1686 resumeHash = hs.sessionState.handshakeHash 1687 } 1688 channelID, err := verifyChannelIDMessage(channelIDMsg, hs.finishedHash.hashForChannelID(resumeHash)) 1689 if err != nil { 1690 return err 1691 } 1692 c.channelID = channelID 1693 1694 hs.writeClientHash(channelIDMsg.marshal()) 1695 } 1696 1697 msg, err := c.readHandshake() 1698 if err != nil { 1699 return err 1700 } 1701 clientFinished, ok := msg.(*finishedMsg) 1702 if !ok { 1703 c.sendAlert(alertUnexpectedMessage) 1704 return unexpectedMessageError(clientFinished, msg) 1705 } 1706 1707 verify := hs.finishedHash.clientSum(hs.masterSecret) 1708 if len(verify) != len(clientFinished.verifyData) || 1709 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 { 1710 c.sendAlert(alertHandshakeFailure) 1711 return errors.New("tls: client's Finished message is incorrect") 1712 } 1713 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...) 1714 copy(out, clientFinished.verifyData) 1715 1716 hs.writeClientHash(clientFinished.marshal()) 1717 return nil 1718} 1719 1720func (hs *serverHandshakeState) sendSessionTicket() error { 1721 c := hs.c 1722 state := sessionState{ 1723 vers: c.vers, 1724 cipherSuite: hs.suite.id, 1725 masterSecret: hs.masterSecret, 1726 certificates: hs.certsFromClient, 1727 handshakeHash: hs.finishedHash.Sum(), 1728 } 1729 1730 if !hs.hello.extensions.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket { 1731 if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 { 1732 c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state) 1733 } 1734 return nil 1735 } 1736 1737 m := new(newSessionTicketMsg) 1738 if c.config.Bugs.SendTicketLifetime != 0 { 1739 m.ticketLifetime = uint32(c.config.Bugs.SendTicketLifetime / time.Second) 1740 } 1741 1742 if !c.config.Bugs.SendEmptySessionTicket { 1743 var err error 1744 m.ticket, err = c.encryptTicket(&state) 1745 if err != nil { 1746 return err 1747 } 1748 } 1749 1750 hs.writeServerHash(m.marshal()) 1751 c.writeRecord(recordTypeHandshake, m.marshal()) 1752 1753 return nil 1754} 1755 1756func (hs *serverHandshakeState) sendFinished(out []byte) error { 1757 c := hs.c 1758 1759 finished := new(finishedMsg) 1760 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret) 1761 copy(out, finished.verifyData) 1762 if c.config.Bugs.BadFinished { 1763 finished.verifyData[0]++ 1764 } 1765 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...) 1766 hs.finishedBytes = finished.marshal() 1767 hs.writeServerHash(hs.finishedBytes) 1768 postCCSBytes := hs.finishedBytes 1769 1770 if c.config.Bugs.FragmentAcrossChangeCipherSpec { 1771 c.writeRecord(recordTypeHandshake, postCCSBytes[:5]) 1772 postCCSBytes = postCCSBytes[5:] 1773 } else if c.config.Bugs.SendUnencryptedFinished { 1774 c.writeRecord(recordTypeHandshake, postCCSBytes) 1775 postCCSBytes = nil 1776 } 1777 c.flushHandshake() 1778 1779 if !c.config.Bugs.SkipChangeCipherSpec { 1780 ccs := []byte{1} 1781 if c.config.Bugs.BadChangeCipherSpec != nil { 1782 ccs = c.config.Bugs.BadChangeCipherSpec 1783 } 1784 c.writeRecord(recordTypeChangeCipherSpec, ccs) 1785 } 1786 1787 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil { 1788 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec) 1789 } 1790 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 { 1791 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec) 1792 return errors.New("tls: simulating post-CCS alert") 1793 } 1794 1795 if !c.config.Bugs.SkipFinished && len(postCCSBytes) > 0 { 1796 c.writeRecord(recordTypeHandshake, postCCSBytes) 1797 if c.config.Bugs.SendExtraFinished { 1798 c.writeRecord(recordTypeHandshake, finished.marshal()) 1799 } 1800 1801 if !c.config.Bugs.PackHelloRequestWithFinished { 1802 // Defer flushing until renegotiation. 1803 c.flushHandshake() 1804 } 1805 } 1806 1807 c.cipherSuite = hs.suite 1808 1809 return nil 1810} 1811 1812// processCertsFromClient takes a chain of client certificates either from a 1813// Certificates message or from a sessionState and verifies them. It returns 1814// the public key of the leaf certificate. 1815func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) { 1816 c := hs.c 1817 1818 hs.certsFromClient = certificates 1819 certs := make([]*x509.Certificate, len(certificates)) 1820 var err error 1821 for i, asn1Data := range certificates { 1822 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil { 1823 c.sendAlert(alertBadCertificate) 1824 return nil, errors.New("tls: failed to parse client certificate: " + err.Error()) 1825 } 1826 } 1827 1828 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 { 1829 opts := x509.VerifyOptions{ 1830 Roots: c.config.ClientCAs, 1831 CurrentTime: c.config.time(), 1832 Intermediates: x509.NewCertPool(), 1833 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, 1834 } 1835 1836 for _, cert := range certs[1:] { 1837 opts.Intermediates.AddCert(cert) 1838 } 1839 1840 chains, err := certs[0].Verify(opts) 1841 if err != nil { 1842 c.sendAlert(alertBadCertificate) 1843 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error()) 1844 } 1845 1846 ok := false 1847 for _, ku := range certs[0].ExtKeyUsage { 1848 if ku == x509.ExtKeyUsageClientAuth { 1849 ok = true 1850 break 1851 } 1852 } 1853 if !ok { 1854 c.sendAlert(alertHandshakeFailure) 1855 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication") 1856 } 1857 1858 c.verifiedChains = chains 1859 } 1860 1861 if len(certs) > 0 { 1862 var pub crypto.PublicKey 1863 switch key := certs[0].PublicKey.(type) { 1864 case *ecdsa.PublicKey, *rsa.PublicKey: 1865 pub = key 1866 default: 1867 c.sendAlert(alertUnsupportedCertificate) 1868 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey) 1869 } 1870 c.peerCertificates = certs 1871 return pub, nil 1872 } 1873 1874 return nil, nil 1875} 1876 1877func verifyChannelIDMessage(channelIDMsg *channelIDMsg, channelIDHash []byte) (*ecdsa.PublicKey, error) { 1878 x := new(big.Int).SetBytes(channelIDMsg.channelID[0:32]) 1879 y := new(big.Int).SetBytes(channelIDMsg.channelID[32:64]) 1880 r := new(big.Int).SetBytes(channelIDMsg.channelID[64:96]) 1881 s := new(big.Int).SetBytes(channelIDMsg.channelID[96:128]) 1882 if !elliptic.P256().IsOnCurve(x, y) { 1883 return nil, errors.New("tls: invalid channel ID public key") 1884 } 1885 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y} 1886 if !ecdsa.Verify(channelID, channelIDHash, r, s) { 1887 return nil, errors.New("tls: invalid channel ID signature") 1888 } 1889 return channelID, nil 1890} 1891 1892func (hs *serverHandshakeState) writeServerHash(msg []byte) { 1893 // writeServerHash is called before writeRecord. 1894 hs.writeHash(msg, hs.c.sendHandshakeSeq) 1895} 1896 1897func (hs *serverHandshakeState) writeClientHash(msg []byte) { 1898 // writeClientHash is called after readHandshake. 1899 hs.writeHash(msg, hs.c.recvHandshakeSeq-1) 1900} 1901 1902func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) { 1903 if hs.c.isDTLS { 1904 // This is somewhat hacky. DTLS hashes a slightly different format. 1905 // First, the TLS header. 1906 hs.finishedHash.Write(msg[:4]) 1907 // Then the sequence number and reassembled fragment offset (always 0). 1908 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0}) 1909 // Then the reassembled fragment (always equal to the message length). 1910 hs.finishedHash.Write(msg[1:4]) 1911 // And then the message body. 1912 hs.finishedHash.Write(msg[4:]) 1913 } else { 1914 hs.finishedHash.Write(msg) 1915 } 1916} 1917 1918// tryCipherSuite returns a cipherSuite with the given id if that cipher suite 1919// is acceptable to use. 1920func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite { 1921 for _, supported := range supportedCipherSuites { 1922 if id == supported { 1923 var candidate *cipherSuite 1924 1925 for _, s := range cipherSuites { 1926 if s.id == id { 1927 candidate = s 1928 break 1929 } 1930 } 1931 if candidate == nil { 1932 continue 1933 } 1934 1935 // Don't select a ciphersuite which we can't 1936 // support for this client. 1937 if version >= VersionTLS13 || candidate.flags&suiteTLS13 != 0 { 1938 if version < VersionTLS13 || candidate.flags&suiteTLS13 == 0 { 1939 continue 1940 } 1941 return candidate 1942 } 1943 if (candidate.flags&suiteECDHE != 0) && !ellipticOk { 1944 continue 1945 } 1946 if (candidate.flags&suiteECDSA != 0) != ecdsaOk { 1947 continue 1948 } 1949 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 { 1950 continue 1951 } 1952 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 { 1953 continue 1954 } 1955 return candidate 1956 } 1957 } 1958 1959 return nil 1960} 1961 1962func isTLS12Cipher(id uint16) bool { 1963 for _, cipher := range cipherSuites { 1964 if cipher.id != id { 1965 continue 1966 } 1967 return cipher.flags&suiteTLS12 != 0 1968 } 1969 // Unknown cipher. 1970 return false 1971} 1972 1973func isGREASEValue(val uint16) bool { 1974 return val&0x0f0f == 0x0a0a && val&0xff == val>>8 1975} 1976 1977func verifyPSKBinder(clientHello *clientHelloMsg, sessionState *sessionState, binderToVerify, transcript []byte) error { 1978 binderLen := 2 1979 for _, binder := range clientHello.pskBinders { 1980 binderLen += 1 + len(binder) 1981 } 1982 1983 truncatedHello := clientHello.marshal() 1984 truncatedHello = truncatedHello[:len(truncatedHello)-binderLen] 1985 pskCipherSuite := cipherSuiteFromID(sessionState.cipherSuite) 1986 if pskCipherSuite == nil { 1987 return errors.New("tls: Unknown cipher suite for PSK in session") 1988 } 1989 1990 binder := computePSKBinder(sessionState.masterSecret, resumptionPSKBinderLabel, pskCipherSuite, transcript, truncatedHello) 1991 if !bytes.Equal(binder, binderToVerify) { 1992 return errors.New("tls: PSK binder does not verify") 1993 } 1994 1995 return nil 1996} 1997