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/ed25519" 12 "crypto/elliptic" 13 "crypto/rsa" 14 "crypto/subtle" 15 "crypto/x509" 16 "errors" 17 "fmt" 18 "io" 19 "math/big" 20 "time" 21 22 "boringssl.googlesource.com/boringssl/ssl/test/runner/hpke" 23) 24 25// serverHandshakeState contains details of a server handshake in progress. 26// It's discarded once the handshake has completed. 27type serverHandshakeState struct { 28 c *Conn 29 clientHello *clientHelloMsg 30 hello *serverHelloMsg 31 suite *cipherSuite 32 ellipticOk bool 33 ecdsaOk bool 34 sessionState *sessionState 35 finishedHash finishedHash 36 masterSecret []byte 37 certsFromClient [][]byte 38 cert *Certificate 39 finishedBytes []byte 40 echHPKEContext *hpke.Context 41 echConfigID uint8 42} 43 44// serverHandshake performs a TLS handshake as a server. 45func (c *Conn) serverHandshake() error { 46 config := c.config 47 48 // If this is the first server handshake, we generate a random key to 49 // encrypt the tickets with. 50 config.serverInitOnce.Do(config.serverInit) 51 52 c.sendHandshakeSeq = 0 53 c.recvHandshakeSeq = 0 54 55 hs := serverHandshakeState{ 56 c: c, 57 } 58 if err := hs.readClientHello(); err != nil { 59 return err 60 } 61 62 if c.vers >= VersionTLS13 { 63 if err := hs.doTLS13Handshake(); err != nil { 64 return err 65 } 66 } else { 67 isResume, err := hs.processClientHello() 68 if err != nil { 69 return err 70 } 71 72 // We only implement enough of SSL 3.0 to test that the client doesn't: 73 // if negotiated (possibly with the NegotiateVersion bug), we send a 74 // ServerHello and look for the resulting client protocol_version alert. 75 if c.vers == VersionSSL30 { 76 c.writeRecord(recordTypeHandshake, hs.hello.marshal()) 77 c.flushHandshake() 78 if _, err := c.readHandshake(); err != nil { 79 return err 80 } 81 return errors.New("tls: client did not reject an SSL 3.0 ServerHello") 82 } 83 84 // For an overview of TLS handshaking, see https://tools.ietf.org/html/rfc5246#section-7.3 85 if isResume { 86 // The client has included a session ticket and so we do an abbreviated handshake. 87 if err := hs.doResumeHandshake(); err != nil { 88 return err 89 } 90 if err := hs.establishKeys(); err != nil { 91 return err 92 } 93 if c.config.Bugs.RenewTicketOnResume { 94 if err := hs.sendSessionTicket(); err != nil { 95 return err 96 } 97 } 98 if err := hs.sendFinished(c.firstFinished[:], isResume); err != nil { 99 return err 100 } 101 // Most retransmits are triggered by a timeout, but the final 102 // leg of the handshake is retransmited upon re-receiving a 103 // Finished. 104 if err := c.simulatePacketLoss(func() { 105 c.sendHandshakeSeq-- 106 c.writeRecord(recordTypeHandshake, hs.finishedBytes) 107 c.flushHandshake() 108 }); err != nil { 109 return err 110 } 111 if err := hs.readFinished(nil, isResume); err != nil { 112 return err 113 } 114 c.didResume = true 115 } else { 116 // The client didn't include a session ticket, or it wasn't 117 // valid so we do a full handshake. 118 if err := hs.doFullHandshake(); err != nil { 119 return err 120 } 121 if err := hs.establishKeys(); err != nil { 122 return err 123 } 124 if err := hs.readFinished(c.firstFinished[:], isResume); err != nil { 125 return err 126 } 127 if c.config.Bugs.AlertBeforeFalseStartTest != 0 { 128 c.sendAlert(c.config.Bugs.AlertBeforeFalseStartTest) 129 } 130 if c.config.Bugs.ExpectFalseStart { 131 if err := c.readRecord(recordTypeApplicationData); err != nil { 132 return fmt.Errorf("tls: peer did not false start: %s", err) 133 } 134 } 135 if err := hs.sendSessionTicket(); err != nil { 136 return err 137 } 138 if err := hs.sendFinished(nil, isResume); err != nil { 139 return err 140 } 141 } 142 143 c.exporterSecret = hs.masterSecret 144 } 145 c.handshakeComplete = true 146 copy(c.clientRandom[:], hs.clientHello.random) 147 copy(c.serverRandom[:], hs.hello.random) 148 149 return nil 150} 151 152// readClientHello reads a ClientHello message from the client and determines 153// the protocol version. 154func (hs *serverHandshakeState) readClientHello() error { 155 config := hs.c.config 156 c := hs.c 157 158 if err := c.simulatePacketLoss(nil); err != nil { 159 return err 160 } 161 msg, err := c.readHandshake() 162 if err != nil { 163 return err 164 } 165 var ok bool 166 hs.clientHello, ok = msg.(*clientHelloMsg) 167 if !ok { 168 c.sendAlert(alertUnexpectedMessage) 169 return unexpectedMessageError(hs.clientHello, msg) 170 } 171 if size := config.Bugs.RequireClientHelloSize; size != 0 && len(hs.clientHello.raw) != size { 172 return fmt.Errorf("tls: ClientHello record size is %d, but expected %d", len(hs.clientHello.raw), size) 173 } 174 if isAllZero(hs.clientHello.random) { 175 // If the client forgets to fill in the client random, it will likely be 176 // all zero. 177 return errors.New("tls: ClientHello random was all zero") 178 } 179 180 if expected := config.Bugs.ExpectOuterServerName; len(expected) != 0 && expected != hs.clientHello.serverName { 181 return fmt.Errorf("tls: unexpected ClientHelloOuter server name: wanted %q, got %q", expected, hs.clientHello.serverName) 182 } 183 184 // We check this both before and after decrypting ECH. 185 if !hs.clientHello.hasGREASEExtension && config.Bugs.ExpectGREASE { 186 return errors.New("tls: no GREASE extension found") 187 } 188 189 if config.Bugs.ExpectClientECH && hs.clientHello.echOuter == nil { 190 return errors.New("tls: expected client to offer ECH") 191 } 192 if config.Bugs.ExpectNoClientECH && hs.clientHello.echOuter != nil { 193 return errors.New("tls: expected client not to offer ECH") 194 } 195 196 if echOuter := hs.clientHello.echOuter; echOuter != nil { 197 for _, candidate := range config.ServerECHConfigs { 198 if candidate.ECHConfig.ConfigID != echOuter.configID { 199 continue 200 } 201 var found bool 202 for _, suite := range candidate.ECHConfig.CipherSuites { 203 if echOuter.kdfID == suite.KDF && echOuter.aeadID == suite.AEAD { 204 found = true 205 break 206 } 207 } 208 if !found { 209 continue 210 } 211 info := []byte("tls ech\x00") 212 info = append(info, candidate.ECHConfig.Raw...) 213 hs.echHPKEContext, err = hpke.SetupBaseReceiverX25519(echOuter.kdfID, echOuter.aeadID, echOuter.enc, candidate.Key, info) 214 if err != nil { 215 continue 216 } 217 clientHelloInner, err := hs.decryptClientHello(hs.clientHello) 218 if err != nil { 219 if _, ok := err.(*echDecryptError); ok { 220 continue 221 } 222 c.sendAlert(alertDecryptError) 223 return fmt.Errorf("tls: error decrypting ClientHello: %s", err) 224 } 225 if config.Bugs.UseInnerSessionWithClientHelloOuter { 226 hs.clientHello.pskIdentities = clientHelloInner.pskIdentities 227 } else { 228 c.echAccepted = true 229 hs.clientHello = clientHelloInner 230 hs.echConfigID = echOuter.configID 231 } 232 } 233 } 234 235 if c.isDTLS && !config.Bugs.SkipHelloVerifyRequest { 236 // Per RFC 6347, the version field in HelloVerifyRequest SHOULD 237 // be always DTLS 1.0 238 cookieLen := c.config.Bugs.HelloVerifyRequestCookieLength 239 if cookieLen == 0 { 240 cookieLen = 32 241 } 242 if c.config.Bugs.EmptyHelloVerifyRequestCookie { 243 cookieLen = 0 244 } 245 helloVerifyRequest := &helloVerifyRequestMsg{ 246 vers: VersionDTLS10, 247 cookie: make([]byte, cookieLen), 248 } 249 if _, err := io.ReadFull(c.config.rand(), helloVerifyRequest.cookie); err != nil { 250 c.sendAlert(alertInternalError) 251 return errors.New("dtls: short read from Rand: " + err.Error()) 252 } 253 c.writeRecord(recordTypeHandshake, helloVerifyRequest.marshal()) 254 c.flushHandshake() 255 256 if err := c.simulatePacketLoss(nil); err != nil { 257 return err 258 } 259 msg, err := c.readHandshake() 260 if err != nil { 261 return err 262 } 263 newClientHello, ok := msg.(*clientHelloMsg) 264 if !ok { 265 c.sendAlert(alertUnexpectedMessage) 266 return unexpectedMessageError(hs.clientHello, msg) 267 } 268 if !bytes.Equal(newClientHello.cookie, helloVerifyRequest.cookie) { 269 return errors.New("dtls: invalid cookie") 270 } 271 if err := checkClientHellosEqual(hs.clientHello.raw, newClientHello.raw, c.isDTLS, nil); err != nil { 272 return err 273 } 274 hs.clientHello = newClientHello 275 } 276 277 if config.Bugs.RequireSameRenegoClientVersion && c.clientVersion != 0 { 278 if c.clientVersion != hs.clientHello.vers { 279 return fmt.Errorf("tls: client offered different version on renego") 280 } 281 } 282 283 if config.Bugs.FailIfKyberOffered { 284 for _, offeredCurve := range hs.clientHello.supportedCurves { 285 if isPqGroup(offeredCurve) { 286 return errors.New("tls: X25519Kyber768 was offered") 287 } 288 } 289 } 290 291 if expected := config.Bugs.ExpectedKeyShares; expected != nil { 292 if len(expected) != len(hs.clientHello.keyShares) { 293 return fmt.Errorf("tls: expected %d key shares, but found %d", len(expected), len(hs.clientHello.keyShares)) 294 } 295 296 for i, group := range expected { 297 if found := hs.clientHello.keyShares[i].group; found != group { 298 return fmt.Errorf("tls: key share #%d is for group %d, not %d", i, found, group) 299 } 300 } 301 } 302 303 c.clientVersion = hs.clientHello.vers 304 305 // Use the versions extension if supplied, otherwise use the legacy ClientHello version. 306 if len(hs.clientHello.supportedVersions) == 0 { 307 if c.isDTLS { 308 if hs.clientHello.vers <= VersionDTLS12 { 309 hs.clientHello.supportedVersions = append(hs.clientHello.supportedVersions, VersionDTLS12) 310 } 311 if hs.clientHello.vers <= VersionDTLS10 { 312 hs.clientHello.supportedVersions = append(hs.clientHello.supportedVersions, VersionDTLS10) 313 } 314 } else { 315 if hs.clientHello.vers >= VersionTLS12 { 316 hs.clientHello.supportedVersions = append(hs.clientHello.supportedVersions, VersionTLS12) 317 } 318 if hs.clientHello.vers >= VersionTLS11 { 319 hs.clientHello.supportedVersions = append(hs.clientHello.supportedVersions, VersionTLS11) 320 } 321 if hs.clientHello.vers >= VersionTLS10 { 322 hs.clientHello.supportedVersions = append(hs.clientHello.supportedVersions, VersionTLS10) 323 } 324 if hs.clientHello.vers >= VersionSSL30 { 325 hs.clientHello.supportedVersions = append(hs.clientHello.supportedVersions, VersionSSL30) 326 } 327 } 328 } else if config.Bugs.ExpectGREASE && !containsGREASE(hs.clientHello.supportedVersions) { 329 return errors.New("tls: no GREASE version value found") 330 } 331 332 if !c.haveVers { 333 if config.Bugs.NegotiateVersion != 0 { 334 c.wireVersion = config.Bugs.NegotiateVersion 335 } else { 336 var found bool 337 for _, vers := range hs.clientHello.supportedVersions { 338 if _, ok := config.isSupportedVersion(vers, c.isDTLS); ok { 339 c.wireVersion = vers 340 found = true 341 break 342 } 343 } 344 if !found { 345 c.sendAlert(alertProtocolVersion) 346 return errors.New("tls: client did not offer any supported protocol versions") 347 } 348 } 349 } else if config.Bugs.NegotiateVersionOnRenego != 0 { 350 c.wireVersion = config.Bugs.NegotiateVersionOnRenego 351 } 352 353 c.vers, ok = wireToVersion(c.wireVersion, c.isDTLS) 354 if !ok { 355 panic("Could not map wire version") 356 } 357 c.haveVers = true 358 359 clientProtocol, ok := wireToVersion(c.clientVersion, c.isDTLS) 360 361 // Reject < 1.2 ClientHellos with signature_algorithms. 362 if ok && clientProtocol < VersionTLS12 && len(hs.clientHello.signatureAlgorithms) > 0 { 363 return fmt.Errorf("tls: client included signature_algorithms before TLS 1.2") 364 } 365 366 // Check the client cipher list is consistent with the version. 367 if ok && clientProtocol < VersionTLS12 { 368 for _, id := range hs.clientHello.cipherSuites { 369 if isTLS12Cipher(id) { 370 return fmt.Errorf("tls: client offered TLS 1.2 cipher before TLS 1.2") 371 } 372 } 373 } 374 375 if config.Bugs.MockQUICTransport != nil && len(hs.clientHello.sessionID) > 0 { 376 return fmt.Errorf("tls: QUIC client did not disable compatibility mode") 377 } 378 if config.Bugs.ExpectNoSessionID && len(hs.clientHello.sessionID) > 0 { 379 return fmt.Errorf("tls: client offered an unexpected session ID") 380 } 381 if config.Bugs.ExpectNoTLS12Session { 382 if len(hs.clientHello.sessionID) > 0 { 383 if _, ok := config.ServerSessionCache.Get(string(hs.clientHello.sessionID)); ok { 384 return fmt.Errorf("tls: client offered an unexpected TLS 1.2 session") 385 } 386 } 387 if len(hs.clientHello.sessionTicket) > 0 { 388 return fmt.Errorf("tls: client offered an unexpected session ticket") 389 } 390 } 391 392 if config.Bugs.ExpectNoTLS13PSK && len(hs.clientHello.pskIdentities) > 0 { 393 return fmt.Errorf("tls: client offered unexpected PSK identities") 394 } 395 396 var scsvFound bool 397 for _, cipherSuite := range hs.clientHello.cipherSuites { 398 if cipherSuite == fallbackSCSV { 399 scsvFound = true 400 break 401 } 402 } 403 404 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV { 405 return errors.New("tls: no fallback SCSV found when expected") 406 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV { 407 return errors.New("tls: fallback SCSV found when not expected") 408 } 409 410 if config.Bugs.ExpectGREASE && !containsGREASE(hs.clientHello.cipherSuites) { 411 return errors.New("tls: no GREASE cipher suite value found") 412 } 413 414 var greaseFound bool 415 for _, curve := range hs.clientHello.supportedCurves { 416 if isGREASEValue(uint16(curve)) { 417 greaseFound = true 418 break 419 } 420 } 421 422 if !greaseFound && config.Bugs.ExpectGREASE { 423 return errors.New("tls: no GREASE curve value found") 424 } 425 426 if len(hs.clientHello.keyShares) > 0 { 427 greaseFound = false 428 for _, keyShare := range hs.clientHello.keyShares { 429 if isGREASEValue(uint16(keyShare.group)) { 430 greaseFound = true 431 break 432 } 433 } 434 435 if !greaseFound && config.Bugs.ExpectGREASE { 436 return errors.New("tls: no GREASE curve value found") 437 } 438 } 439 440 if len(hs.clientHello.sessionID) == 0 && c.config.Bugs.ExpectClientHelloSessionID { 441 return errors.New("tls: expected non-empty session ID from client") 442 } 443 444 applyBugsToClientHello(hs.clientHello, config) 445 446 return nil 447} 448 449func applyBugsToClientHello(clientHello *clientHelloMsg, config *Config) { 450 if config.Bugs.IgnorePeerSignatureAlgorithmPreferences { 451 clientHello.signatureAlgorithms = config.signSignatureAlgorithms() 452 } 453 if config.Bugs.IgnorePeerCurvePreferences { 454 clientHello.supportedCurves = config.curvePreferences() 455 } 456 if config.Bugs.IgnorePeerCipherPreferences { 457 clientHello.cipherSuites = config.cipherSuites() 458 } 459} 460 461type echDecryptError struct { 462 error 463} 464 465func (hs *serverHandshakeState) decryptClientHello(helloOuter *clientHelloMsg) (helloInner *clientHelloMsg, err error) { 466 // ClientHelloOuterAAD is ClientHelloOuter with the payload replaced by 467 // zeros. See draft-ietf-tls-esni-13, section 5.2. 468 aad := make([]byte, len(helloOuter.raw)-4) 469 copy(aad, helloOuter.raw[4:helloOuter.echPayloadStart]) 470 copy(aad[helloOuter.echPayloadEnd-4:], helloOuter.raw[helloOuter.echPayloadEnd:]) 471 472 // In fuzzer mode, the payload is cleartext. 473 encoded := helloOuter.echOuter.payload 474 if !hs.c.config.Bugs.NullAllCiphers { 475 var err error 476 encoded, err = hs.echHPKEContext.Open(helloOuter.echOuter.payload, aad) 477 if err != nil { 478 // Wrap |err| so the caller can implement trial decryption. 479 return nil, &echDecryptError{err} 480 } 481 } 482 483 helloInner, err = decodeClientHelloInner(hs.c.config, encoded, helloOuter) 484 if err != nil { 485 return nil, err 486 } 487 488 if isAllZero(helloInner.random) { 489 // If the client forgets to fill in the client random, it will likely be 490 // all zero. 491 return nil, errors.New("tls: ClientHelloInner random was all zero") 492 } 493 if bytes.Equal(helloInner.random, helloOuter.random) { 494 return nil, errors.New("tls: ClientHelloOuter and ClientHelloInner have the same random values") 495 } 496 // ClientHelloInner should not offer TLS 1.2 and below. 497 if len(helloInner.supportedVersions) == 0 { 498 return nil, errors.New("tls: ClientHelloInner did not offer supported_versions") 499 } 500 for _, vers := range helloInner.supportedVersions { 501 switch vers { 502 case VersionSSL30, VersionTLS10, VersionTLS11, VersionTLS12, VersionDTLS10, VersionDTLS12: 503 return nil, fmt.Errorf("tls: ClientHelloInner offered invalid version: %04x", vers) 504 } 505 } 506 // ClientHelloInner should omit TLS-1.2-only extensions. 507 if helloInner.nextProtoNeg || len(helloInner.supportedPoints) != 0 || helloInner.ticketSupported || helloInner.secureRenegotiation != nil || helloInner.extendedMasterSecret { 508 return nil, errors.New("tls: ClientHelloInner included a TLS-1.2-only extension") 509 } 510 if !helloInner.echInner { 511 return nil, errors.New("tls: ClientHelloInner missing inner encrypted_client_hello extension") 512 } 513 514 return helloInner, nil 515} 516 517func (hs *serverHandshakeState) doTLS13Handshake() error { 518 c := hs.c 519 config := c.config 520 521 // We've read the ClientHello, so the next record must be preceded with ChangeCipherSpec. 522 c.expectTLS13ChangeCipherSpec = true 523 524 hs.hello = &serverHelloMsg{ 525 isDTLS: c.isDTLS, 526 vers: c.wireVersion, 527 sessionID: hs.clientHello.sessionID, 528 compressionMethod: config.Bugs.SendCompressionMethod, 529 versOverride: config.Bugs.SendServerHelloVersion, 530 supportedVersOverride: config.Bugs.SendServerSupportedVersionExtension, 531 omitSupportedVers: config.Bugs.OmitServerSupportedVersionExtension, 532 customExtension: config.Bugs.CustomUnencryptedExtension, 533 unencryptedALPN: config.Bugs.SendUnencryptedALPN, 534 } 535 536 hs.hello.random = make([]byte, 32) 537 if _, err := io.ReadFull(config.rand(), hs.hello.random); err != nil { 538 c.sendAlert(alertInternalError) 539 return err 540 } 541 542 // TLS 1.3 forbids clients from advertising any non-null compression. 543 if len(hs.clientHello.compressionMethods) != 1 || hs.clientHello.compressionMethods[0] != compressionNone { 544 return errors.New("tls: client sent compression method other than null for TLS 1.3") 545 } 546 547 // Prepare an EncryptedExtensions message, but do not send it yet. 548 encryptedExtensions := new(encryptedExtensionsMsg) 549 encryptedExtensions.empty = config.Bugs.EmptyEncryptedExtensions 550 if err := hs.processClientExtensions(&encryptedExtensions.extensions); err != nil { 551 return err 552 } 553 554 // Select the cipher suite. 555 var preferenceList, supportedList []uint16 556 if config.PreferServerCipherSuites { 557 preferenceList = config.cipherSuites() 558 supportedList = hs.clientHello.cipherSuites 559 } else { 560 preferenceList = hs.clientHello.cipherSuites 561 supportedList = config.cipherSuites() 562 } 563 564 for _, id := range preferenceList { 565 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, true, true); hs.suite != nil { 566 break 567 } 568 } 569 570 if hs.suite == nil { 571 c.sendAlert(alertHandshakeFailure) 572 return errors.New("tls: no cipher suite supported by both client and server") 573 } 574 575 hs.hello.cipherSuite = hs.suite.id 576 if c.config.Bugs.SendCipherSuite != 0 { 577 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite 578 } 579 580 hs.finishedHash = newFinishedHash(c.wireVersion, c.isDTLS, hs.suite) 581 hs.finishedHash.discardHandshakeBuffer() 582 hs.writeClientHash(hs.clientHello.marshal()) 583 584 supportedCurve := false 585 var selectedCurve CurveID 586 preferredCurves := config.curvePreferences() 587Curves: 588 for _, curve := range hs.clientHello.supportedCurves { 589 for _, supported := range preferredCurves { 590 if supported == curve { 591 supportedCurve = true 592 selectedCurve = curve 593 break Curves 594 } 595 } 596 } 597 598 if !supportedCurve { 599 c.sendAlert(alertHandshakeFailure) 600 return errors.New("tls: no curve supported by both client and server") 601 } 602 603 pskIdentities := hs.clientHello.pskIdentities 604 pskKEModes := hs.clientHello.pskKEModes 605 606 var replacedPSKIdentities bool 607 if len(pskIdentities) == 0 && len(hs.clientHello.sessionTicket) > 0 && c.config.Bugs.AcceptAnySession { 608 // Pick up the ticket from the TLS 1.2 extension, to test the 609 // client does not get in a mixed up state. 610 psk := pskIdentity{ 611 ticket: hs.clientHello.sessionTicket, 612 } 613 pskIdentities = []pskIdentity{psk} 614 pskKEModes = []byte{pskDHEKEMode} 615 replacedPSKIdentities = true 616 } 617 if config.Bugs.UseInnerSessionWithClientHelloOuter { 618 replacedPSKIdentities = true 619 } 620 621 var pskIndex int 622 foundKEMode := bytes.IndexByte(pskKEModes, pskDHEKEMode) >= 0 623 if foundKEMode && !config.SessionTicketsDisabled { 624 for i, pskIdentity := range pskIdentities { 625 // TODO(svaldez): Check the obfuscatedTicketAge before accepting 0-RTT. 626 sessionState, ok := c.decryptTicket(pskIdentity.ticket) 627 if !ok { 628 continue 629 } 630 631 if !config.Bugs.AcceptAnySession { 632 if sessionState.vers != c.vers { 633 continue 634 } 635 if sessionState.ticketExpiration.Before(c.config.time()) { 636 continue 637 } 638 sessionCipher := cipherSuiteFromID(sessionState.cipherSuite) 639 if sessionCipher == nil || sessionCipher.hash() != hs.suite.hash() { 640 continue 641 } 642 } 643 644 clientTicketAge := time.Duration(uint32(pskIdentity.obfuscatedTicketAge-sessionState.ticketAgeAdd)) * time.Millisecond 645 if config.Bugs.ExpectTicketAge != 0 && clientTicketAge != config.Bugs.ExpectTicketAge { 646 c.sendAlert(alertHandshakeFailure) 647 return errors.New("tls: invalid ticket age") 648 } 649 650 if !replacedPSKIdentities { 651 binderToVerify := hs.clientHello.pskBinders[i] 652 if err := verifyPSKBinder(c.wireVersion, hs.clientHello, sessionState, binderToVerify, []byte{}, []byte{}); err != nil { 653 return err 654 } 655 } 656 657 hs.sessionState = sessionState 658 hs.hello.hasPSKIdentity = true 659 hs.hello.pskIdentity = uint16(i) 660 pskIndex = i 661 if config.Bugs.SelectPSKIdentityOnResume != 0 { 662 hs.hello.pskIdentity = config.Bugs.SelectPSKIdentityOnResume 663 } 664 c.didResume = true 665 break 666 } 667 } 668 669 if config.Bugs.AlwaysSelectPSKIdentity { 670 hs.hello.hasPSKIdentity = true 671 hs.hello.pskIdentity = 0 672 } 673 674 // Resolve PSK and compute the early secret. 675 if hs.sessionState != nil { 676 hs.finishedHash.addEntropy(hs.sessionState.secret) 677 } else { 678 hs.finishedHash.addEntropy(hs.finishedHash.zeroSecret()) 679 } 680 681 hs.hello.hasKeyShare = true 682 if hs.sessionState != nil && config.Bugs.NegotiatePSKResumption { 683 hs.hello.hasKeyShare = false 684 } 685 if config.Bugs.MissingKeyShare { 686 hs.hello.hasKeyShare = false 687 } 688 689 firstHelloRetryRequest := true 690 691ResendHelloRetryRequest: 692 var sendHelloRetryRequest bool 693 cipherSuite := hs.suite.id 694 if config.Bugs.SendHelloRetryRequestCipherSuite != 0 { 695 cipherSuite = config.Bugs.SendHelloRetryRequestCipherSuite 696 } 697 helloRetryRequest := &helloRetryRequestMsg{ 698 vers: c.wireVersion, 699 sessionID: hs.clientHello.sessionID, 700 cipherSuite: cipherSuite, 701 compressionMethod: config.Bugs.SendCompressionMethod, 702 duplicateExtensions: config.Bugs.DuplicateHelloRetryRequestExtensions, 703 } 704 705 if config.Bugs.AlwaysSendHelloRetryRequest { 706 sendHelloRetryRequest = true 707 } 708 709 if config.Bugs.SendHelloRetryRequestCookie != nil { 710 sendHelloRetryRequest = true 711 helloRetryRequest.cookie = config.Bugs.SendHelloRetryRequestCookie 712 } 713 714 if len(config.Bugs.CustomHelloRetryRequestExtension) > 0 { 715 sendHelloRetryRequest = true 716 helloRetryRequest.customExtension = config.Bugs.CustomHelloRetryRequestExtension 717 } 718 719 var selectedKeyShare *keyShareEntry 720 if hs.hello.hasKeyShare { 721 // Look for the key share corresponding to our selected curve. 722 for i := range hs.clientHello.keyShares { 723 if hs.clientHello.keyShares[i].group == selectedCurve { 724 selectedKeyShare = &hs.clientHello.keyShares[i] 725 break 726 } 727 } 728 729 if config.Bugs.ExpectMissingKeyShare && selectedKeyShare != nil { 730 return errors.New("tls: expected missing key share") 731 } 732 733 if selectedKeyShare == nil { 734 helloRetryRequest.hasSelectedGroup = true 735 helloRetryRequest.selectedGroup = selectedCurve 736 sendHelloRetryRequest = true 737 } 738 } 739 740 if config.Bugs.SendHelloRetryRequestCurve != 0 { 741 helloRetryRequest.hasSelectedGroup = true 742 helloRetryRequest.selectedGroup = config.Bugs.SendHelloRetryRequestCurve 743 sendHelloRetryRequest = true 744 } 745 746 if config.Bugs.SkipHelloRetryRequest { 747 sendHelloRetryRequest = false 748 } 749 750 if sendHelloRetryRequest { 751 hs.finishedHash.UpdateForHelloRetryRequest() 752 753 // Emit the ECH confirmation signal when requested. 754 if hs.clientHello.echInner { 755 helloRetryRequest.echConfirmation = make([]byte, 8) 756 helloRetryRequest.echConfirmation = hs.finishedHash.echAcceptConfirmation(hs.clientHello.random, echAcceptConfirmationHRRLabel, helloRetryRequest.marshal()) 757 helloRetryRequest.raw = nil 758 } else if config.Bugs.AlwaysSendECHHelloRetryRequest { 759 // When solicited, a random ECH confirmation string should be ignored. 760 helloRetryRequest.echConfirmation = make([]byte, 8) 761 if _, err := io.ReadFull(config.rand(), helloRetryRequest.echConfirmation); err != nil { 762 c.sendAlert(alertInternalError) 763 return fmt.Errorf("tls: short read from Rand: %s", err) 764 } 765 } 766 767 hs.writeServerHash(helloRetryRequest.marshal()) 768 if c.config.Bugs.PartialServerHelloWithHelloRetryRequest { 769 data := helloRetryRequest.marshal() 770 c.writeRecord(recordTypeHandshake, append(data[:len(data):len(data)], typeServerHello)) 771 } else { 772 c.writeRecord(recordTypeHandshake, helloRetryRequest.marshal()) 773 } 774 c.flushHandshake() 775 776 if !c.config.Bugs.SkipChangeCipherSpec { 777 c.writeRecord(recordTypeChangeCipherSpec, []byte{1}) 778 } 779 780 if hs.clientHello.hasEarlyData { 781 c.setSkipEarlyData() 782 } 783 784 // Read new ClientHello. 785 newMsg, err := c.readHandshake() 786 if err != nil { 787 return err 788 } 789 newClientHello, ok := newMsg.(*clientHelloMsg) 790 if !ok { 791 c.sendAlert(alertUnexpectedMessage) 792 return unexpectedMessageError(newClientHello, newMsg) 793 } 794 795 if expected := config.Bugs.ExpectOuterServerName; len(expected) != 0 && expected != newClientHello.serverName { 796 return fmt.Errorf("tls: unexpected ClientHelloOuter server name: wanted %q, got %q", expected, newClientHello.serverName) 797 } 798 799 if c.echAccepted { 800 if newClientHello.echOuter == nil { 801 c.sendAlert(alertMissingExtension) 802 return errors.New("tls: second ClientHelloOuter had no encrypted_client_hello extension") 803 } 804 if newClientHello.echOuter.configID != hs.echConfigID || 805 newClientHello.echOuter.kdfID != hs.echHPKEContext.KDF() || 806 newClientHello.echOuter.aeadID != hs.echHPKEContext.AEAD() { 807 c.sendAlert(alertIllegalParameter) 808 return errors.New("tls: ECH parameters changed in second ClientHelloOuter") 809 } 810 if len(newClientHello.echOuter.enc) != 0 { 811 c.sendAlert(alertIllegalParameter) 812 return errors.New("tls: second ClientHelloOuter had non-empty ECH enc") 813 } 814 newClientHello, err = hs.decryptClientHello(newClientHello) 815 if err != nil { 816 c.sendAlert(alertDecryptError) 817 return fmt.Errorf("tls: error decrypting ClientHello: %s", err) 818 } 819 } 820 821 hs.writeClientHash(newClientHello.marshal()) 822 823 if config.Bugs.ExpectNoTLS13PSKAfterHRR && len(newClientHello.pskIdentities) > 0 { 824 return fmt.Errorf("tls: client offered unexpected PSK identities after HelloRetryRequest") 825 } 826 827 applyBugsToClientHello(newClientHello, config) 828 829 // Check that the new ClientHello matches the old ClientHello, 830 // except for relevant modifications. See RFC 8446, section 4.1.2. 831 ignoreExtensions := []uint16{extensionPadding} 832 833 if helloRetryRequest.hasSelectedGroup { 834 newKeyShares := newClientHello.keyShares 835 if len(newKeyShares) != 1 || newKeyShares[0].group != helloRetryRequest.selectedGroup { 836 return errors.New("tls: KeyShare from HelloRetryRequest not in new ClientHello") 837 } 838 selectedKeyShare = &newKeyShares[0] 839 ignoreExtensions = append(ignoreExtensions, extensionKeyShare) 840 } 841 842 if len(helloRetryRequest.cookie) > 0 { 843 if !bytes.Equal(newClientHello.tls13Cookie, helloRetryRequest.cookie) { 844 return errors.New("tls: cookie from HelloRetryRequest not present in new ClientHello") 845 } 846 ignoreExtensions = append(ignoreExtensions, extensionCookie) 847 } 848 849 // The second ClientHello refreshes binders, and may drop PSK identities 850 // that are no longer consistent with the cipher suite. 851 oldPSKIdentities := hs.clientHello.pskIdentities 852 for _, identity := range newClientHello.pskIdentities { 853 // Skip to the matching PSK identity in oldPSKIdentities. 854 for len(oldPSKIdentities) > 0 && !bytes.Equal(oldPSKIdentities[0].ticket, identity.ticket) { 855 oldPSKIdentities = oldPSKIdentities[1:] 856 } 857 // The identity now either matches, or oldPSKIdentities is empty. 858 if len(oldPSKIdentities) == 0 { 859 return errors.New("tls: unexpected PSK identity in second ClientHello") 860 } 861 oldPSKIdentities = oldPSKIdentities[1:] 862 } 863 ignoreExtensions = append(ignoreExtensions, extensionPreSharedKey) 864 865 // Update the index for the identity we resumed. The client may have 866 // dropped some entries. 867 if hs.sessionState != nil { 868 var found bool 869 ticket := hs.clientHello.pskIdentities[pskIndex].ticket 870 for i, identity := range newClientHello.pskIdentities { 871 if bytes.Equal(identity.ticket, ticket) { 872 found = true 873 pskIndex = i 874 break 875 } 876 } 877 if found { 878 binderToVerify := newClientHello.pskBinders[pskIndex] 879 if err := verifyPSKBinder(c.wireVersion, newClientHello, hs.sessionState, binderToVerify, hs.clientHello.marshal(), helloRetryRequest.marshal()); err != nil { 880 return err 881 } 882 } else if !config.Bugs.AcceptAnySession { 883 // If AcceptAnySession is set, the client may have already noticed 884 // the selected session is incompatible with the HelloRetryRequest 885 // and correctly dropped the PSK identity. We may also have 886 // attempted to resume a session from the TLS 1.2 extension. 887 return errors.New("tls: second ClientHello is missing selected session") 888 } 889 } 890 891 // The second ClientHello must stop offering early data. 892 if newClientHello.hasEarlyData { 893 return errors.New("tls: EarlyData sent in new ClientHello") 894 } 895 ignoreExtensions = append(ignoreExtensions, extensionEarlyData) 896 897 if err := checkClientHellosEqual(hs.clientHello.raw, newClientHello.raw, c.isDTLS, ignoreExtensions); err != nil { 898 return err 899 } 900 901 if firstHelloRetryRequest && config.Bugs.SecondHelloRetryRequest { 902 firstHelloRetryRequest = false 903 goto ResendHelloRetryRequest 904 } 905 } 906 907 // Decide whether or not to accept early data. 908 if !sendHelloRetryRequest && hs.clientHello.hasEarlyData { 909 if !config.Bugs.AlwaysRejectEarlyData && hs.sessionState != nil { 910 if hs.sessionState.cipherSuite == hs.suite.id && 911 c.clientProtocol == string(hs.sessionState.earlyALPN) && 912 c.hasApplicationSettings == hs.sessionState.hasApplicationSettings && 913 bytes.Equal(c.localApplicationSettings, hs.sessionState.localApplicationSettings) { 914 encryptedExtensions.extensions.hasEarlyData = true 915 } 916 if config.Bugs.AlwaysAcceptEarlyData { 917 encryptedExtensions.extensions.hasEarlyData = true 918 } 919 } 920 if encryptedExtensions.extensions.hasEarlyData { 921 earlyTrafficSecret := hs.finishedHash.deriveSecret(earlyTrafficLabel) 922 c.earlyExporterSecret = hs.finishedHash.deriveSecret(earlyExporterLabel) 923 924 // Applications are implicit with early data. 925 if !config.Bugs.SendApplicationSettingsWithEarlyData { 926 encryptedExtensions.extensions.hasApplicationSettings = false 927 encryptedExtensions.extensions.applicationSettings = nil 928 } 929 930 sessionCipher := cipherSuiteFromID(hs.sessionState.cipherSuite) 931 if err := c.useInTrafficSecret(encryptionEarlyData, c.wireVersion, sessionCipher, earlyTrafficSecret); err != nil { 932 return err 933 } 934 935 for _, expectedMsg := range config.Bugs.ExpectEarlyData { 936 if err := c.readRecord(recordTypeApplicationData); err != nil { 937 return err 938 } 939 msg := c.input.data[c.input.off:] 940 if !bytes.Equal(msg, expectedMsg) { 941 return fmt.Errorf("tls: got early data record %x, wanted %x", msg, expectedMsg) 942 } 943 c.in.freeBlock(c.input) 944 c.input = nil 945 } 946 } else { 947 c.setSkipEarlyData() 948 } 949 } 950 951 if config.Bugs.SendEarlyDataExtension { 952 encryptedExtensions.extensions.hasEarlyData = true 953 } 954 955 // Resolve ECDHE and compute the handshake secret. 956 if hs.hello.hasKeyShare { 957 // Once a curve has been selected and a key share identified, 958 // the server needs to generate a public value and send it in 959 // the ServerHello. 960 kem, ok := kemForCurveID(selectedCurve, config) 961 if !ok { 962 panic("tls: server failed to look up curve ID") 963 } 964 c.curveID = selectedCurve 965 966 var peerKey []byte 967 if config.Bugs.SkipHelloRetryRequest { 968 // If skipping HelloRetryRequest, use a random key to 969 // avoid crashing. 970 kem2, _ := kemForCurveID(selectedCurve, config) 971 var err error 972 peerKey, err = kem2.generate(config.rand()) 973 if err != nil { 974 return err 975 } 976 } else { 977 peerKey = selectedKeyShare.keyExchange 978 } 979 980 ciphertext, ecdheSecret, err := kem.encap(config.rand(), peerKey) 981 if err != nil { 982 c.sendAlert(alertHandshakeFailure) 983 return err 984 } 985 hs.finishedHash.nextSecret() 986 hs.finishedHash.addEntropy(ecdheSecret) 987 hs.hello.hasKeyShare = true 988 989 curveID := selectedCurve 990 if c.config.Bugs.SendCurve != 0 { 991 curveID = config.Bugs.SendCurve 992 } 993 if c.config.Bugs.InvalidECDHPoint { 994 ciphertext[0] ^= 0xff 995 } 996 997 hs.hello.keyShare = keyShareEntry{ 998 group: curveID, 999 keyExchange: ciphertext, 1000 } 1001 1002 if config.Bugs.EncryptedExtensionsWithKeyShare { 1003 encryptedExtensions.extensions.hasKeyShare = true 1004 encryptedExtensions.extensions.keyShare = keyShareEntry{ 1005 group: curveID, 1006 keyExchange: ciphertext, 1007 } 1008 } 1009 } else { 1010 hs.finishedHash.nextSecret() 1011 hs.finishedHash.addEntropy(hs.finishedHash.zeroSecret()) 1012 } 1013 1014 // Emit the ECH confirmation signal when requested. 1015 if hs.clientHello.echInner && !config.Bugs.OmitServerHelloECHConfirmation { 1016 randomSuffix := hs.hello.random[len(hs.hello.random)-echAcceptConfirmationLength:] 1017 for i := range randomSuffix { 1018 randomSuffix[i] = 0 1019 } 1020 copy(randomSuffix, hs.finishedHash.echAcceptConfirmation(hs.clientHello.random, echAcceptConfirmationLabel, hs.hello.marshal())) 1021 hs.hello.raw = nil 1022 } 1023 1024 // Send unencrypted ServerHello. 1025 helloBytes := hs.hello.marshal() 1026 hs.writeServerHash(helloBytes) 1027 if config.Bugs.PartialServerHelloWithHelloRetryRequest { 1028 // The first byte has already been written. 1029 helloBytes = helloBytes[1:] 1030 } 1031 if config.Bugs.PartialEncryptedExtensionsWithServerHello { 1032 c.writeRecord(recordTypeHandshake, append(helloBytes[:len(helloBytes):len(helloBytes)], typeEncryptedExtensions)) 1033 } else { 1034 c.writeRecord(recordTypeHandshake, helloBytes) 1035 } 1036 c.flushHandshake() 1037 1038 if !c.config.Bugs.SkipChangeCipherSpec && !sendHelloRetryRequest { 1039 c.writeRecord(recordTypeChangeCipherSpec, []byte{1}) 1040 } 1041 1042 for i := 0; i < c.config.Bugs.SendExtraChangeCipherSpec; i++ { 1043 c.writeRecord(recordTypeChangeCipherSpec, []byte{1}) 1044 } 1045 1046 // Switch to handshake traffic keys. 1047 serverHandshakeTrafficSecret := hs.finishedHash.deriveSecret(serverHandshakeTrafficLabel) 1048 c.useOutTrafficSecret(encryptionHandshake, c.wireVersion, hs.suite, serverHandshakeTrafficSecret) 1049 // Derive handshake traffic read key, but don't switch yet. 1050 clientHandshakeTrafficSecret := hs.finishedHash.deriveSecret(clientHandshakeTrafficLabel) 1051 1052 // Send EncryptedExtensions. 1053 hs.writeServerHash(encryptedExtensions.marshal()) 1054 if config.Bugs.PartialEncryptedExtensionsWithServerHello { 1055 // The first byte has already been sent. 1056 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()[1:]) 1057 } else { 1058 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()) 1059 } 1060 1061 if hs.sessionState == nil { 1062 if config.ClientAuth >= RequestClientCert { 1063 // Request a client certificate 1064 certReq := &certificateRequestMsg{ 1065 vers: c.wireVersion, 1066 hasSignatureAlgorithm: !config.Bugs.OmitCertificateRequestAlgorithms, 1067 hasRequestContext: true, 1068 requestContext: config.Bugs.SendRequestContext, 1069 customExtension: config.Bugs.SendCustomCertificateRequest, 1070 } 1071 if !config.Bugs.NoSignatureAlgorithms { 1072 certReq.signatureAlgorithms = config.verifySignatureAlgorithms() 1073 } 1074 1075 // An empty list of certificateAuthorities signals to 1076 // the client that it may send any certificate in response 1077 // to our request. When we know the CAs we trust, then 1078 // we can send them down, so that the client can choose 1079 // an appropriate certificate to give to us. 1080 if config.ClientCAs != nil { 1081 certReq.certificateAuthorities = config.ClientCAs.Subjects() 1082 } 1083 hs.writeServerHash(certReq.marshal()) 1084 c.writeRecord(recordTypeHandshake, certReq.marshal()) 1085 } 1086 1087 certMsg := &certificateMsg{ 1088 hasRequestContext: true, 1089 } 1090 if !config.Bugs.EmptyCertificateList { 1091 for i, certData := range hs.cert.Certificate { 1092 cert := certificateEntry{ 1093 data: certData, 1094 } 1095 if i == 0 { 1096 if hs.clientHello.ocspStapling && !c.config.Bugs.NoOCSPStapling { 1097 cert.ocspResponse = hs.cert.OCSPStaple 1098 } 1099 if hs.clientHello.sctListSupported && !c.config.Bugs.NoSignedCertificateTimestamps { 1100 cert.sctList = hs.cert.SignedCertificateTimestampList 1101 } 1102 cert.duplicateExtensions = config.Bugs.SendDuplicateCertExtensions 1103 cert.extraExtension = config.Bugs.SendExtensionOnCertificate 1104 } else { 1105 if config.Bugs.SendOCSPOnIntermediates != nil { 1106 cert.ocspResponse = config.Bugs.SendOCSPOnIntermediates 1107 } 1108 if config.Bugs.SendSCTOnIntermediates != nil { 1109 cert.sctList = config.Bugs.SendSCTOnIntermediates 1110 } 1111 } 1112 certMsg.certificates = append(certMsg.certificates, cert) 1113 } 1114 } 1115 certMsgBytes := certMsg.marshal() 1116 sentCompressedCertMsg := false 1117 1118 FindCertCompressionAlg: 1119 for candidate, alg := range c.config.CertCompressionAlgs { 1120 for _, id := range hs.clientHello.compressedCertAlgs { 1121 if id == candidate { 1122 if expected := config.Bugs.ExpectedCompressedCert; expected != 0 && expected != id { 1123 return fmt.Errorf("tls: expected to send compressed cert with alg %d, but picked %d", expected, id) 1124 } 1125 if config.Bugs.ExpectUncompressedCert { 1126 return errors.New("tls: expected to send uncompressed cert") 1127 } 1128 1129 if override := config.Bugs.SendCertCompressionAlgID; override != 0 { 1130 id = override 1131 } 1132 1133 uncompressed := certMsgBytes[4:] 1134 uncompressedLen := uint32(len(uncompressed)) 1135 if override := config.Bugs.SendCertUncompressedLength; override != 0 { 1136 uncompressedLen = override 1137 } 1138 1139 compressedCertMsgBytes := (&compressedCertificateMsg{ 1140 algID: id, 1141 uncompressedLength: uncompressedLen, 1142 compressed: alg.Compress(uncompressed), 1143 }).marshal() 1144 1145 hs.writeServerHash(compressedCertMsgBytes) 1146 c.writeRecord(recordTypeHandshake, compressedCertMsgBytes) 1147 sentCompressedCertMsg = true 1148 break FindCertCompressionAlg 1149 } 1150 } 1151 } 1152 1153 if !sentCompressedCertMsg { 1154 if config.Bugs.ExpectedCompressedCert != 0 { 1155 return errors.New("tls: unexpectedly sent uncompressed certificate") 1156 } 1157 hs.writeServerHash(certMsgBytes) 1158 c.writeRecord(recordTypeHandshake, certMsgBytes) 1159 } 1160 1161 certVerify := &certificateVerifyMsg{ 1162 hasSignatureAlgorithm: true, 1163 } 1164 1165 // Determine the hash to sign. 1166 privKey := hs.cert.PrivateKey 1167 1168 var err error 1169 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, config, hs.clientHello.signatureAlgorithms) 1170 if err != nil { 1171 c.sendAlert(alertInternalError) 1172 return err 1173 } 1174 1175 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13) 1176 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input) 1177 if err != nil { 1178 c.sendAlert(alertInternalError) 1179 return err 1180 } 1181 1182 if config.Bugs.SendSignatureAlgorithm != 0 { 1183 certVerify.signatureAlgorithm = config.Bugs.SendSignatureAlgorithm 1184 } 1185 1186 if !config.Bugs.SkipCertificateVerify { 1187 hs.writeServerHash(certVerify.marshal()) 1188 c.writeRecord(recordTypeHandshake, certVerify.marshal()) 1189 } 1190 } else if hs.sessionState != nil { 1191 // Pick up certificates from the session instead. 1192 if len(hs.sessionState.certificates) > 0 { 1193 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil { 1194 return err 1195 } 1196 } 1197 } 1198 1199 finished := new(finishedMsg) 1200 finished.verifyData = hs.finishedHash.serverSum(serverHandshakeTrafficSecret) 1201 if config.Bugs.BadFinished { 1202 finished.verifyData[0]++ 1203 } 1204 hs.writeServerHash(finished.marshal()) 1205 c.writeRecord(recordTypeHandshake, finished.marshal()) 1206 if c.config.Bugs.SendExtraFinished { 1207 c.writeRecord(recordTypeHandshake, finished.marshal()) 1208 } 1209 c.flushHandshake() 1210 1211 if encryptedExtensions.extensions.hasEarlyData && !c.shouldSkipEarlyData() { 1212 for _, expectedMsg := range config.Bugs.ExpectLateEarlyData { 1213 if err := c.readRecord(recordTypeApplicationData); err != nil { 1214 return err 1215 } 1216 if !bytes.Equal(c.input.data[c.input.off:], expectedMsg) { 1217 return errors.New("ExpectLateEarlyData: did not get expected message") 1218 } 1219 c.in.freeBlock(c.input) 1220 c.input = nil 1221 } 1222 } 1223 1224 // The various secrets do not incorporate the client's final leg, so 1225 // derive them now before updating the handshake context. 1226 hs.finishedHash.nextSecret() 1227 hs.finishedHash.addEntropy(hs.finishedHash.zeroSecret()) 1228 1229 clientTrafficSecret := hs.finishedHash.deriveSecret(clientApplicationTrafficLabel) 1230 serverTrafficSecret := hs.finishedHash.deriveSecret(serverApplicationTrafficLabel) 1231 c.exporterSecret = hs.finishedHash.deriveSecret(exporterLabel) 1232 1233 // Switch to application data keys on write. In particular, any alerts 1234 // from the client certificate are sent over these keys. 1235 c.useOutTrafficSecret(encryptionApplication, c.wireVersion, hs.suite, serverTrafficSecret) 1236 1237 // Send 0.5-RTT messages. 1238 for _, halfRTTMsg := range config.Bugs.SendHalfRTTData { 1239 if _, err := c.writeRecord(recordTypeApplicationData, halfRTTMsg); err != nil { 1240 return err 1241 } 1242 } 1243 1244 // Read end_of_early_data. 1245 if encryptedExtensions.extensions.hasEarlyData && config.Bugs.MockQUICTransport == nil { 1246 msg, err := c.readHandshake() 1247 if err != nil { 1248 return err 1249 } 1250 1251 endOfEarlyData, ok := msg.(*endOfEarlyDataMsg) 1252 if !ok { 1253 c.sendAlert(alertUnexpectedMessage) 1254 return unexpectedMessageError(endOfEarlyData, msg) 1255 } 1256 hs.writeClientHash(endOfEarlyData.marshal()) 1257 } 1258 1259 // Switch input stream to handshake traffic keys. 1260 if err := c.useInTrafficSecret(encryptionHandshake, c.wireVersion, hs.suite, clientHandshakeTrafficSecret); err != nil { 1261 return err 1262 } 1263 1264 // If we sent an ALPS extension, the client must respond with one. 1265 if encryptedExtensions.extensions.hasApplicationSettings { 1266 msg, err := c.readHandshake() 1267 if err != nil { 1268 return err 1269 } 1270 clientEncryptedExtensions, ok := msg.(*clientEncryptedExtensionsMsg) 1271 if !ok { 1272 c.sendAlert(alertUnexpectedMessage) 1273 return unexpectedMessageError(clientEncryptedExtensions, msg) 1274 } 1275 hs.writeClientHash(clientEncryptedExtensions.marshal()) 1276 1277 if !clientEncryptedExtensions.hasApplicationSettings { 1278 c.sendAlert(alertMissingExtension) 1279 return errors.New("tls: client didn't provide application settings") 1280 } 1281 c.peerApplicationSettings = clientEncryptedExtensions.applicationSettings 1282 } else if encryptedExtensions.extensions.hasEarlyData { 1283 // 0-RTT sessions carry application settings over. 1284 c.peerApplicationSettings = hs.sessionState.peerApplicationSettings 1285 } 1286 1287 // If we requested a client certificate, then the client must send a 1288 // certificate message, even if it's empty. 1289 if config.ClientAuth >= RequestClientCert { 1290 msg, err := c.readHandshake() 1291 if err != nil { 1292 return err 1293 } 1294 1295 certMsg, ok := msg.(*certificateMsg) 1296 if !ok { 1297 c.sendAlert(alertUnexpectedMessage) 1298 return unexpectedMessageError(certMsg, msg) 1299 } 1300 hs.writeClientHash(certMsg.marshal()) 1301 1302 if len(certMsg.certificates) == 0 { 1303 // The client didn't actually send a certificate 1304 switch config.ClientAuth { 1305 case RequireAnyClientCert, RequireAndVerifyClientCert: 1306 c.sendAlert(alertCertificateRequired) 1307 return errors.New("tls: client didn't provide a certificate") 1308 } 1309 } 1310 1311 var certs [][]byte 1312 for _, cert := range certMsg.certificates { 1313 certs = append(certs, cert.data) 1314 // OCSP responses and SCT lists are not negotiated in 1315 // client certificates. 1316 if cert.ocspResponse != nil || cert.sctList != nil { 1317 c.sendAlert(alertUnsupportedExtension) 1318 return errors.New("tls: unexpected extensions in the client certificate") 1319 } 1320 } 1321 pub, err := hs.processCertsFromClient(certs) 1322 if err != nil { 1323 return err 1324 } 1325 1326 if len(c.peerCertificates) > 0 { 1327 msg, err = c.readHandshake() 1328 if err != nil { 1329 return err 1330 } 1331 1332 certVerify, ok := msg.(*certificateVerifyMsg) 1333 if !ok { 1334 c.sendAlert(alertUnexpectedMessage) 1335 return unexpectedMessageError(certVerify, msg) 1336 } 1337 1338 c.peerSignatureAlgorithm = certVerify.signatureAlgorithm 1339 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13) 1340 if err := verifyMessage(c.vers, pub, config, certVerify.signatureAlgorithm, input, certVerify.signature); err != nil { 1341 c.sendAlert(alertBadCertificate) 1342 return err 1343 } 1344 hs.writeClientHash(certVerify.marshal()) 1345 } 1346 } 1347 1348 if encryptedExtensions.extensions.channelIDRequested { 1349 msg, err := c.readHandshake() 1350 if err != nil { 1351 return err 1352 } 1353 channelIDMsg, ok := msg.(*channelIDMsg) 1354 if !ok { 1355 c.sendAlert(alertUnexpectedMessage) 1356 return unexpectedMessageError(channelIDMsg, msg) 1357 } 1358 channelIDHash := crypto.SHA256.New() 1359 channelIDHash.Write(hs.finishedHash.certificateVerifyInput(channelIDContextTLS13)) 1360 channelID, err := verifyChannelIDMessage(channelIDMsg, channelIDHash.Sum(nil)) 1361 if err != nil { 1362 return err 1363 } 1364 c.channelID = channelID 1365 1366 hs.writeClientHash(channelIDMsg.marshal()) 1367 } 1368 1369 // Read the client Finished message. 1370 msg, err := c.readHandshake() 1371 if err != nil { 1372 return err 1373 } 1374 clientFinished, ok := msg.(*finishedMsg) 1375 if !ok { 1376 c.sendAlert(alertUnexpectedMessage) 1377 return unexpectedMessageError(clientFinished, msg) 1378 } 1379 1380 verify := hs.finishedHash.clientSum(clientHandshakeTrafficSecret) 1381 if len(verify) != len(clientFinished.verifyData) || 1382 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 { 1383 c.sendAlert(alertHandshakeFailure) 1384 return errors.New("tls: client's Finished message was incorrect") 1385 } 1386 hs.writeClientHash(clientFinished.marshal()) 1387 1388 // Switch to application data keys on read. 1389 if err := c.useInTrafficSecret(encryptionApplication, c.wireVersion, hs.suite, clientTrafficSecret); err != nil { 1390 return err 1391 } 1392 1393 c.cipherSuite = hs.suite 1394 c.resumptionSecret = hs.finishedHash.deriveSecret(resumptionLabel) 1395 1396 // TODO(davidben): Allow configuring the number of tickets sent for 1397 // testing. 1398 if !c.config.SessionTicketsDisabled && foundKEMode { 1399 ticketCount := 2 1400 for i := 0; i < ticketCount; i++ { 1401 c.SendNewSessionTicket([]byte{byte(i)}) 1402 } 1403 } 1404 return nil 1405} 1406 1407// processClientHello processes the ClientHello message from the client and 1408// decides whether we will perform session resumption. 1409func (hs *serverHandshakeState) processClientHello() (isResume bool, err error) { 1410 config := hs.c.config 1411 c := hs.c 1412 1413 hs.hello = &serverHelloMsg{ 1414 isDTLS: c.isDTLS, 1415 vers: c.wireVersion, 1416 versOverride: config.Bugs.SendServerHelloVersion, 1417 compressionMethod: config.Bugs.SendCompressionMethod, 1418 extensions: serverExtensions{ 1419 supportedVersion: config.Bugs.SendServerSupportedVersionExtension, 1420 }, 1421 omitExtensions: config.Bugs.OmitExtensions, 1422 emptyExtensions: config.Bugs.EmptyExtensions, 1423 } 1424 1425 hs.hello.random = make([]byte, 32) 1426 _, err = io.ReadFull(config.rand(), hs.hello.random) 1427 if err != nil { 1428 c.sendAlert(alertInternalError) 1429 return false, err 1430 } 1431 1432 _, supportsTLS13 := c.config.isSupportedVersion(VersionTLS13, false) 1433 1434 // Signal downgrades in the server random, per RFC 8446, section 4.1.3. 1435 if supportsTLS13 || config.Bugs.SendTLS13DowngradeRandom { 1436 if c.vers <= VersionTLS12 && config.maxVersion(c.isDTLS) >= VersionTLS13 { 1437 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS13) 1438 } 1439 if c.vers <= VersionTLS11 && config.maxVersion(c.isDTLS) == VersionTLS12 { 1440 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS12) 1441 } 1442 } 1443 if config.Bugs.SendJDK11DowngradeRandom { 1444 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeJDK11) 1445 } 1446 1447 foundCompression := false 1448 // We only support null compression, so check that the client offered it. 1449 for _, compression := range hs.clientHello.compressionMethods { 1450 if compression == compressionNone { 1451 foundCompression = true 1452 break 1453 } 1454 } 1455 1456 if !foundCompression { 1457 c.sendAlert(alertHandshakeFailure) 1458 return false, errors.New("tls: client does not support uncompressed connections") 1459 } 1460 1461 if err := hs.processClientExtensions(&hs.hello.extensions); err != nil { 1462 return false, err 1463 } 1464 1465 supportedCurve := false 1466 preferredCurves := config.curvePreferences() 1467Curves: 1468 for _, curve := range hs.clientHello.supportedCurves { 1469 if isPqGroup(curve) && c.vers < VersionTLS13 { 1470 // Post-quantum is TLS 1.3 only. 1471 continue 1472 } 1473 1474 for _, supported := range preferredCurves { 1475 if supported == curve { 1476 supportedCurve = true 1477 break Curves 1478 } 1479 } 1480 } 1481 1482 supportedPointFormat := false 1483 for _, pointFormat := range hs.clientHello.supportedPoints { 1484 if pointFormat == pointFormatUncompressed { 1485 supportedPointFormat = true 1486 break 1487 } 1488 } 1489 hs.ellipticOk = supportedCurve && supportedPointFormat 1490 1491 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey) 1492 // Ed25519 also uses ECDSA certificates. 1493 _, ed25519Ok := hs.cert.PrivateKey.(ed25519.PrivateKey) 1494 hs.ecdsaOk = hs.ecdsaOk || ed25519Ok 1495 1496 // For test purposes, check that the peer never offers a session when 1497 // renegotiating. 1498 if c.cipherSuite != nil && len(hs.clientHello.sessionID) > 0 && c.config.Bugs.FailIfResumeOnRenego { 1499 return false, errors.New("tls: offered resumption on renegotiation") 1500 } 1501 1502 if hs.checkForResumption() { 1503 return true, nil 1504 } 1505 1506 var preferenceList, supportedList []uint16 1507 if c.config.PreferServerCipherSuites { 1508 preferenceList = c.config.cipherSuites() 1509 supportedList = hs.clientHello.cipherSuites 1510 } else { 1511 preferenceList = hs.clientHello.cipherSuites 1512 supportedList = c.config.cipherSuites() 1513 } 1514 1515 for _, id := range preferenceList { 1516 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil { 1517 break 1518 } 1519 } 1520 1521 if hs.suite == nil { 1522 c.sendAlert(alertHandshakeFailure) 1523 return false, errors.New("tls: no cipher suite supported by both client and server") 1524 } 1525 1526 return false, nil 1527} 1528 1529// processClientExtensions processes all ClientHello extensions not directly 1530// related to cipher suite negotiation and writes responses in serverExtensions. 1531func (hs *serverHandshakeState) processClientExtensions(serverExtensions *serverExtensions) error { 1532 config := hs.c.config 1533 c := hs.c 1534 1535 if c.vers < VersionTLS13 || config.Bugs.NegotiateRenegotiationInfoAtAllVersions { 1536 if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) { 1537 c.sendAlert(alertHandshakeFailure) 1538 return errors.New("tls: renegotiation mismatch") 1539 } 1540 1541 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo { 1542 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.clientVerify...) 1543 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.serverVerify...) 1544 if c.config.Bugs.BadRenegotiationInfo { 1545 serverExtensions.secureRenegotiation[0] ^= 0x80 1546 } 1547 if c.config.Bugs.BadRenegotiationInfoEnd { 1548 serverExtensions.secureRenegotiation[len(serverExtensions.secureRenegotiation)-1] ^= 0x80 1549 } 1550 } else { 1551 serverExtensions.secureRenegotiation = hs.clientHello.secureRenegotiation 1552 } 1553 1554 if c.noRenegotiationInfo() { 1555 serverExtensions.secureRenegotiation = nil 1556 } 1557 } 1558 1559 serverExtensions.duplicateExtension = c.config.Bugs.DuplicateExtension 1560 1561 if len(hs.clientHello.serverName) > 0 { 1562 c.serverName = hs.clientHello.serverName 1563 } 1564 if len(config.Certificates) == 0 { 1565 c.sendAlert(alertInternalError) 1566 return errors.New("tls: no certificates configured") 1567 } 1568 hs.cert = &config.Certificates[0] 1569 if len(hs.clientHello.serverName) > 0 { 1570 hs.cert = config.getCertificateForName(hs.clientHello.serverName) 1571 } 1572 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName { 1573 return fmt.Errorf("tls: unexpected server name: wanted %q, got %q", expected, hs.clientHello.serverName) 1574 } 1575 1576 if cert := config.Bugs.RenegotiationCertificate; c.cipherSuite != nil && cert != nil { 1577 hs.cert = cert 1578 } 1579 1580 if len(hs.clientHello.alpnProtocols) > 0 { 1581 // We will never offer ALPN as a client on renegotiation 1582 // handshakes. 1583 if len(c.clientVerify) > 0 { 1584 return errors.New("tls: offered ALPN on renegotiation") 1585 } 1586 if proto := c.config.Bugs.ALPNProtocol; proto != nil { 1587 serverExtensions.alpnProtocol = *proto 1588 serverExtensions.alpnProtocolEmpty = len(*proto) == 0 1589 c.clientProtocol = *proto 1590 c.usedALPN = true 1591 } else if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback { 1592 serverExtensions.alpnProtocol = selectedProto 1593 c.clientProtocol = selectedProto 1594 c.usedALPN = true 1595 } 1596 1597 var alpsAllowed bool 1598 if c.vers >= VersionTLS13 { 1599 for _, proto := range hs.clientHello.alpsProtocols { 1600 if proto == c.clientProtocol { 1601 alpsAllowed = true 1602 break 1603 } 1604 } 1605 } 1606 if c.config.Bugs.AlwaysNegotiateApplicationSettings { 1607 alpsAllowed = true 1608 } 1609 if settings, ok := c.config.ApplicationSettings[c.clientProtocol]; ok && alpsAllowed { 1610 c.hasApplicationSettings = true 1611 c.localApplicationSettings = settings 1612 // Note these fields may later be cleared we accept 0-RTT. 1613 serverExtensions.hasApplicationSettings = true 1614 serverExtensions.applicationSettings = settings 1615 } 1616 } 1617 1618 if len(c.config.Bugs.SendALPN) > 0 { 1619 serverExtensions.alpnProtocol = c.config.Bugs.SendALPN 1620 } 1621 1622 if c.vers < VersionTLS13 || config.Bugs.NegotiateNPNAtAllVersions { 1623 if len(hs.clientHello.alpnProtocols) == 0 || c.config.Bugs.NegotiateALPNAndNPN { 1624 // Although sending an empty NPN extension is reasonable, Firefox has 1625 // had a bug around this. Best to send nothing at all if 1626 // config.NextProtos is empty. See 1627 // https://code.google.com/p/go/issues/detail?id=5445. 1628 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 { 1629 serverExtensions.nextProtoNeg = true 1630 serverExtensions.nextProtos = config.NextProtos 1631 serverExtensions.npnAfterAlpn = config.Bugs.SwapNPNAndALPN 1632 } 1633 } 1634 } 1635 1636 if len(hs.clientHello.quicTransportParams) > 0 { 1637 c.quicTransportParams = hs.clientHello.quicTransportParams 1638 } 1639 if c.config.QUICTransportParamsUseLegacyCodepoint.IncludeStandard() { 1640 serverExtensions.quicTransportParams = c.config.QUICTransportParams 1641 } 1642 1643 if len(hs.clientHello.quicTransportParamsLegacy) > 0 { 1644 c.quicTransportParamsLegacy = hs.clientHello.quicTransportParamsLegacy 1645 } 1646 if c.config.QUICTransportParamsUseLegacyCodepoint.IncludeLegacy() { 1647 serverExtensions.quicTransportParamsLegacy = c.config.QUICTransportParams 1648 } 1649 1650 if c.vers < VersionTLS13 || config.Bugs.NegotiateEMSAtAllVersions { 1651 disableEMS := config.Bugs.NoExtendedMasterSecret 1652 if c.cipherSuite != nil { 1653 disableEMS = config.Bugs.NoExtendedMasterSecretOnRenegotiation 1654 } 1655 serverExtensions.extendedMasterSecret = hs.clientHello.extendedMasterSecret && !disableEMS 1656 } 1657 1658 if config.Bugs.AlwaysNegotiateChannelID || (hs.clientHello.channelIDSupported && config.RequestChannelID) { 1659 serverExtensions.channelIDRequested = true 1660 } 1661 1662 if hs.clientHello.srtpProtectionProfiles != nil { 1663 SRTPLoop: 1664 for _, p1 := range c.config.SRTPProtectionProfiles { 1665 for _, p2 := range hs.clientHello.srtpProtectionProfiles { 1666 if p1 == p2 { 1667 serverExtensions.srtpProtectionProfile = p1 1668 c.srtpProtectionProfile = p1 1669 break SRTPLoop 1670 } 1671 } 1672 } 1673 } 1674 1675 if c.config.Bugs.SendSRTPProtectionProfile != 0 { 1676 serverExtensions.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile 1677 } 1678 1679 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil { 1680 if hs.clientHello.customExtension != *expected { 1681 return fmt.Errorf("tls: bad custom extension contents %q", hs.clientHello.customExtension) 1682 } 1683 } 1684 serverExtensions.customExtension = config.Bugs.CustomExtension 1685 1686 if c.config.Bugs.AdvertiseTicketExtension { 1687 serverExtensions.ticketSupported = true 1688 } 1689 1690 if c.config.Bugs.SendSupportedPointFormats != nil { 1691 serverExtensions.supportedPoints = c.config.Bugs.SendSupportedPointFormats 1692 } 1693 1694 if c.config.Bugs.SendServerSupportedCurves { 1695 serverExtensions.supportedCurves = c.config.curvePreferences() 1696 } 1697 1698 if !hs.clientHello.hasGREASEExtension && config.Bugs.ExpectGREASE { 1699 return errors.New("tls: no GREASE extension found") 1700 } 1701 1702 serverExtensions.serverNameAck = c.config.Bugs.SendServerNameAck 1703 1704 if (c.vers >= VersionTLS13 && hs.clientHello.echOuter != nil) || c.config.Bugs.AlwaysSendECHRetryConfigs { 1705 if len(config.Bugs.SendECHRetryConfigs) > 0 { 1706 serverExtensions.echRetryConfigs = config.Bugs.SendECHRetryConfigs 1707 } else if len(config.ServerECHConfigs) > 0 { 1708 echConfigs := make([][]byte, len(config.ServerECHConfigs)) 1709 for i, echConfig := range config.ServerECHConfigs { 1710 echConfigs[i] = echConfig.ECHConfig.Raw 1711 } 1712 serverExtensions.echRetryConfigs = CreateECHConfigList(echConfigs...) 1713 } 1714 } 1715 1716 return nil 1717} 1718 1719// checkForResumption returns true if we should perform resumption on this connection. 1720func (hs *serverHandshakeState) checkForResumption() bool { 1721 c := hs.c 1722 1723 ticket := hs.clientHello.sessionTicket 1724 if len(ticket) == 0 && len(hs.clientHello.pskIdentities) > 0 && c.config.Bugs.AcceptAnySession { 1725 ticket = hs.clientHello.pskIdentities[0].ticket 1726 } 1727 if len(ticket) > 0 { 1728 if c.config.SessionTicketsDisabled { 1729 return false 1730 } 1731 1732 var ok bool 1733 if hs.sessionState, ok = c.decryptTicket(ticket); !ok { 1734 return false 1735 } 1736 } else { 1737 if c.config.ServerSessionCache == nil { 1738 return false 1739 } 1740 1741 var ok bool 1742 sessionID := string(hs.clientHello.sessionID) 1743 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionID); !ok { 1744 return false 1745 } 1746 } 1747 1748 if c.config.Bugs.AcceptAnySession { 1749 // Replace the cipher suite with one known to work, to test 1750 // cross-version resumption attempts. 1751 hs.sessionState.cipherSuite = TLS_RSA_WITH_AES_128_CBC_SHA 1752 } else { 1753 // Never resume a session for a different SSL version. 1754 if c.vers != hs.sessionState.vers { 1755 return false 1756 } 1757 1758 cipherSuiteOk := false 1759 // Check that the client is still offering the ciphersuite in the session. 1760 for _, id := range hs.clientHello.cipherSuites { 1761 if id == hs.sessionState.cipherSuite { 1762 cipherSuiteOk = true 1763 break 1764 } 1765 } 1766 if !cipherSuiteOk { 1767 return false 1768 } 1769 } 1770 1771 // Check that we also support the ciphersuite from the session. 1772 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), c.vers, hs.ellipticOk, hs.ecdsaOk) 1773 1774 if hs.suite == nil { 1775 return false 1776 } 1777 1778 sessionHasClientCerts := len(hs.sessionState.certificates) != 0 1779 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert 1780 if needClientCerts && !sessionHasClientCerts { 1781 return false 1782 } 1783 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert { 1784 return false 1785 } 1786 1787 return true 1788} 1789 1790func (hs *serverHandshakeState) doResumeHandshake() error { 1791 c := hs.c 1792 1793 hs.hello.cipherSuite = hs.suite.id 1794 if c.config.Bugs.SendCipherSuite != 0 { 1795 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite 1796 } 1797 // We echo the client's session ID in the ServerHello to let it know 1798 // that we're doing a resumption. 1799 hs.hello.sessionID = hs.clientHello.sessionID 1800 hs.hello.extensions.ticketSupported = c.config.Bugs.RenewTicketOnResume 1801 1802 if c.config.Bugs.SendSCTListOnResume != nil { 1803 hs.hello.extensions.sctList = c.config.Bugs.SendSCTListOnResume 1804 } 1805 1806 if c.config.Bugs.SendOCSPResponseOnResume != nil { 1807 // There is no way, syntactically, to send an OCSP response on a 1808 // resumption handshake. 1809 hs.hello.extensions.ocspStapling = true 1810 } 1811 1812 hs.finishedHash = newFinishedHash(c.wireVersion, c.isDTLS, hs.suite) 1813 hs.finishedHash.discardHandshakeBuffer() 1814 hs.writeClientHash(hs.clientHello.marshal()) 1815 hs.writeServerHash(hs.hello.marshal()) 1816 1817 c.writeRecord(recordTypeHandshake, hs.hello.marshal()) 1818 1819 if len(hs.sessionState.certificates) > 0 { 1820 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil { 1821 return err 1822 } 1823 } 1824 1825 hs.masterSecret = hs.sessionState.secret 1826 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret 1827 1828 return nil 1829} 1830 1831func (hs *serverHandshakeState) doFullHandshake() error { 1832 config := hs.c.config 1833 c := hs.c 1834 1835 isPSK := hs.suite.flags&suitePSK != 0 1836 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 && !c.config.Bugs.NoOCSPStapling { 1837 hs.hello.extensions.ocspStapling = true 1838 } 1839 1840 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 && !c.config.Bugs.NoSignedCertificateTimestamps { 1841 hs.hello.extensions.sctList = hs.cert.SignedCertificateTimestampList 1842 } 1843 1844 if len(c.clientVerify) > 0 && config.Bugs.SendSCTListOnRenegotiation != nil { 1845 hs.hello.extensions.sctList = config.Bugs.SendSCTListOnRenegotiation 1846 } 1847 1848 hs.hello.extensions.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled 1849 hs.hello.cipherSuite = hs.suite.id 1850 if config.Bugs.SendCipherSuite != 0 { 1851 hs.hello.cipherSuite = config.Bugs.SendCipherSuite 1852 } 1853 c.extendedMasterSecret = hs.hello.extensions.extendedMasterSecret 1854 1855 // Generate a session ID if we're to save the session. 1856 if !hs.hello.extensions.ticketSupported && config.ServerSessionCache != nil { 1857 l := config.Bugs.NewSessionIDLength 1858 if l == 0 { 1859 l = 32 1860 } 1861 hs.hello.sessionID = make([]byte, l) 1862 if _, err := io.ReadFull(config.rand(), hs.hello.sessionID); err != nil { 1863 c.sendAlert(alertInternalError) 1864 return errors.New("tls: short read from Rand: " + err.Error()) 1865 } 1866 } 1867 if config.Bugs.EchoSessionIDInFullHandshake { 1868 hs.hello.sessionID = hs.clientHello.sessionID 1869 } 1870 1871 hs.finishedHash = newFinishedHash(c.wireVersion, c.isDTLS, hs.suite) 1872 hs.writeClientHash(hs.clientHello.marshal()) 1873 hs.writeServerHash(hs.hello.marshal()) 1874 1875 if config.Bugs.SendSNIWarningAlert { 1876 c.SendAlert(alertLevelWarning, alertUnrecognizedName) 1877 } 1878 1879 c.writeRecord(recordTypeHandshake, hs.hello.marshal()) 1880 1881 if !isPSK { 1882 certMsg := new(certificateMsg) 1883 if !config.Bugs.EmptyCertificateList { 1884 for _, certData := range hs.cert.Certificate { 1885 certMsg.certificates = append(certMsg.certificates, certificateEntry{ 1886 data: certData, 1887 }) 1888 } 1889 } 1890 if !config.Bugs.UnauthenticatedECDH { 1891 certMsgBytes := certMsg.marshal() 1892 hs.writeServerHash(certMsgBytes) 1893 c.writeRecord(recordTypeHandshake, certMsgBytes) 1894 } 1895 } 1896 1897 if hs.hello.extensions.ocspStapling && !c.config.Bugs.SkipCertificateStatus { 1898 certStatus := new(certificateStatusMsg) 1899 certStatus.statusType = statusTypeOCSP 1900 certStatus.response = hs.cert.OCSPStaple 1901 if len(c.clientVerify) > 0 && config.Bugs.SendOCSPResponseOnRenegotiation != nil { 1902 certStatus.response = config.Bugs.SendOCSPResponseOnRenegotiation 1903 } 1904 hs.writeServerHash(certStatus.marshal()) 1905 c.writeRecord(recordTypeHandshake, certStatus.marshal()) 1906 } 1907 1908 keyAgreement := hs.suite.ka(c.vers) 1909 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello, c.vers) 1910 if err != nil { 1911 c.sendAlert(alertHandshakeFailure) 1912 return err 1913 } 1914 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok { 1915 c.curveID = ecdhe.curveID 1916 } 1917 if skx != nil && !config.Bugs.SkipServerKeyExchange { 1918 hs.writeServerHash(skx.marshal()) 1919 c.writeRecord(recordTypeHandshake, skx.marshal()) 1920 } 1921 1922 if config.ClientAuth >= RequestClientCert { 1923 // Request a client certificate 1924 certReq := &certificateRequestMsg{ 1925 vers: c.wireVersion, 1926 certificateTypes: config.ClientCertificateTypes, 1927 } 1928 if certReq.certificateTypes == nil { 1929 certReq.certificateTypes = []byte{ 1930 byte(CertTypeRSASign), 1931 byte(CertTypeECDSASign), 1932 } 1933 } 1934 if c.vers >= VersionTLS12 { 1935 certReq.hasSignatureAlgorithm = true 1936 if !config.Bugs.NoSignatureAlgorithms { 1937 certReq.signatureAlgorithms = config.verifySignatureAlgorithms() 1938 } 1939 } 1940 1941 // An empty list of certificateAuthorities signals to 1942 // the client that it may send any certificate in response 1943 // to our request. When we know the CAs we trust, then 1944 // we can send them down, so that the client can choose 1945 // an appropriate certificate to give to us. 1946 if config.ClientCAs != nil { 1947 certReq.certificateAuthorities = config.ClientCAs.Subjects() 1948 } 1949 hs.writeServerHash(certReq.marshal()) 1950 c.writeRecord(recordTypeHandshake, certReq.marshal()) 1951 } 1952 1953 helloDone := new(serverHelloDoneMsg) 1954 helloDoneBytes := helloDone.marshal() 1955 hs.writeServerHash(helloDoneBytes) 1956 var toAppend byte 1957 if config.Bugs.PartialNewSessionTicketWithServerHelloDone { 1958 toAppend = typeNewSessionTicket 1959 } else if config.Bugs.PartialFinishedWithServerHelloDone { 1960 toAppend = typeFinished 1961 } 1962 if toAppend != 0 { 1963 c.writeRecord(recordTypeHandshake, append(helloDoneBytes[:len(helloDoneBytes):len(helloDoneBytes)], toAppend)) 1964 } else { 1965 c.writeRecord(recordTypeHandshake, helloDoneBytes) 1966 } 1967 c.flushHandshake() 1968 1969 var pub crypto.PublicKey // public key for client auth, if any 1970 1971 if err := c.simulatePacketLoss(nil); err != nil { 1972 return err 1973 } 1974 msg, err := c.readHandshake() 1975 if err != nil { 1976 return err 1977 } 1978 1979 // If we requested a client certificate, then the client must send a 1980 // certificate message, even if it's empty. 1981 if config.ClientAuth >= RequestClientCert { 1982 certMsg, ok := msg.(*certificateMsg) 1983 if !ok { 1984 c.sendAlert(alertUnexpectedMessage) 1985 return unexpectedMessageError(certMsg, msg) 1986 } 1987 hs.writeClientHash(certMsg.marshal()) 1988 1989 if len(certMsg.certificates) == 0 { 1990 // The client didn't actually send a certificate 1991 switch config.ClientAuth { 1992 case RequireAnyClientCert, RequireAndVerifyClientCert: 1993 c.sendAlert(alertBadCertificate) 1994 return errors.New("tls: client didn't provide a certificate") 1995 } 1996 } 1997 1998 var certificates [][]byte 1999 for _, cert := range certMsg.certificates { 2000 certificates = append(certificates, cert.data) 2001 } 2002 2003 pub, err = hs.processCertsFromClient(certificates) 2004 if err != nil { 2005 return err 2006 } 2007 2008 msg, err = c.readHandshake() 2009 if err != nil { 2010 return err 2011 } 2012 } 2013 2014 // Get client key exchange 2015 ckx, ok := msg.(*clientKeyExchangeMsg) 2016 if !ok { 2017 c.sendAlert(alertUnexpectedMessage) 2018 return unexpectedMessageError(ckx, msg) 2019 } 2020 hs.writeClientHash(ckx.marshal()) 2021 2022 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers) 2023 if err != nil { 2024 c.sendAlert(alertHandshakeFailure) 2025 return err 2026 } 2027 if c.extendedMasterSecret { 2028 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash) 2029 } else { 2030 if c.config.Bugs.RequireExtendedMasterSecret { 2031 return errors.New("tls: extended master secret required but not supported by peer") 2032 } 2033 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random) 2034 } 2035 2036 // If we received a client cert in response to our certificate request message, 2037 // the client will send us a certificateVerifyMsg immediately after the 2038 // clientKeyExchangeMsg. This message is a digest of all preceding 2039 // handshake-layer messages that is signed using the private key corresponding 2040 // to the client's certificate. This allows us to verify that the client is in 2041 // possession of the private key of the certificate. 2042 if len(c.peerCertificates) > 0 { 2043 msg, err = c.readHandshake() 2044 if err != nil { 2045 return err 2046 } 2047 certVerify, ok := msg.(*certificateVerifyMsg) 2048 if !ok { 2049 c.sendAlert(alertUnexpectedMessage) 2050 return unexpectedMessageError(certVerify, msg) 2051 } 2052 2053 // Determine the signature type. 2054 var sigAlg signatureAlgorithm 2055 if certVerify.hasSignatureAlgorithm { 2056 sigAlg = certVerify.signatureAlgorithm 2057 c.peerSignatureAlgorithm = sigAlg 2058 } 2059 2060 if err := verifyMessage(c.vers, pub, c.config, sigAlg, hs.finishedHash.buffer, certVerify.signature); err != nil { 2061 c.sendAlert(alertBadCertificate) 2062 return errors.New("could not validate signature of connection nonces: " + err.Error()) 2063 } 2064 2065 hs.writeClientHash(certVerify.marshal()) 2066 } 2067 2068 hs.finishedHash.discardHandshakeBuffer() 2069 2070 return nil 2071} 2072 2073func (hs *serverHandshakeState) establishKeys() error { 2074 c := hs.c 2075 2076 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV := 2077 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen(c.vers)) 2078 2079 var clientCipher, serverCipher interface{} 2080 var clientHash, serverHash macFunction 2081 2082 if hs.suite.aead == nil { 2083 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */) 2084 clientHash = hs.suite.mac(c.vers, clientMAC) 2085 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */) 2086 serverHash = hs.suite.mac(c.vers, serverMAC) 2087 } else { 2088 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV) 2089 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV) 2090 } 2091 2092 c.in.prepareCipherSpec(c.wireVersion, clientCipher, clientHash) 2093 c.out.prepareCipherSpec(c.wireVersion, serverCipher, serverHash) 2094 2095 return nil 2096} 2097 2098func (hs *serverHandshakeState) readFinished(out []byte, isResume bool) error { 2099 c := hs.c 2100 2101 c.readRecord(recordTypeChangeCipherSpec) 2102 if err := c.in.error(); err != nil { 2103 return err 2104 } 2105 2106 if hs.hello.extensions.nextProtoNeg { 2107 msg, err := c.readHandshake() 2108 if err != nil { 2109 return err 2110 } 2111 nextProto, ok := msg.(*nextProtoMsg) 2112 if !ok { 2113 c.sendAlert(alertUnexpectedMessage) 2114 return unexpectedMessageError(nextProto, msg) 2115 } 2116 hs.writeClientHash(nextProto.marshal()) 2117 c.clientProtocol = nextProto.proto 2118 } 2119 2120 if hs.hello.extensions.channelIDRequested { 2121 msg, err := c.readHandshake() 2122 if err != nil { 2123 return err 2124 } 2125 channelIDMsg, ok := msg.(*channelIDMsg) 2126 if !ok { 2127 c.sendAlert(alertUnexpectedMessage) 2128 return unexpectedMessageError(channelIDMsg, msg) 2129 } 2130 var resumeHash []byte 2131 if isResume { 2132 resumeHash = hs.sessionState.handshakeHash 2133 } 2134 channelID, err := verifyChannelIDMessage(channelIDMsg, hs.finishedHash.hashForChannelID(resumeHash)) 2135 if err != nil { 2136 return err 2137 } 2138 c.channelID = channelID 2139 2140 hs.writeClientHash(channelIDMsg.marshal()) 2141 } 2142 2143 msg, err := c.readHandshake() 2144 if err != nil { 2145 return err 2146 } 2147 clientFinished, ok := msg.(*finishedMsg) 2148 if !ok { 2149 c.sendAlert(alertUnexpectedMessage) 2150 return unexpectedMessageError(clientFinished, msg) 2151 } 2152 2153 verify := hs.finishedHash.clientSum(hs.masterSecret) 2154 if len(verify) != len(clientFinished.verifyData) || 2155 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 { 2156 c.sendAlert(alertHandshakeFailure) 2157 return errors.New("tls: client's Finished message is incorrect") 2158 } 2159 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...) 2160 copy(out, clientFinished.verifyData) 2161 2162 hs.writeClientHash(clientFinished.marshal()) 2163 return nil 2164} 2165 2166func (hs *serverHandshakeState) sendSessionTicket() error { 2167 c := hs.c 2168 state := sessionState{ 2169 vers: c.vers, 2170 cipherSuite: hs.suite.id, 2171 secret: hs.masterSecret, 2172 certificates: hs.certsFromClient, 2173 handshakeHash: hs.finishedHash.Sum(), 2174 } 2175 2176 if !hs.hello.extensions.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket { 2177 if c.config.ServerSessionCache != nil && len(hs.hello.sessionID) != 0 { 2178 c.config.ServerSessionCache.Put(string(hs.hello.sessionID), &state) 2179 } 2180 return nil 2181 } 2182 2183 m := new(newSessionTicketMsg) 2184 m.vers = c.wireVersion 2185 m.isDTLS = c.isDTLS 2186 if c.config.Bugs.SendTicketLifetime != 0 { 2187 m.ticketLifetime = uint32(c.config.Bugs.SendTicketLifetime / time.Second) 2188 } 2189 2190 if !c.config.Bugs.SendEmptySessionTicket { 2191 var err error 2192 m.ticket, err = c.encryptTicket(&state) 2193 if err != nil { 2194 return err 2195 } 2196 } 2197 2198 hs.writeServerHash(m.marshal()) 2199 if c.config.Bugs.PartialNewSessionTicketWithServerHelloDone { 2200 // The first byte was already sent. 2201 c.writeRecord(recordTypeHandshake, m.marshal()[1:]) 2202 } else { 2203 c.writeRecord(recordTypeHandshake, m.marshal()) 2204 } 2205 2206 return nil 2207} 2208 2209func (hs *serverHandshakeState) sendFinished(out []byte, isResume bool) error { 2210 c := hs.c 2211 2212 finished := new(finishedMsg) 2213 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret) 2214 copy(out, finished.verifyData) 2215 if c.config.Bugs.BadFinished { 2216 finished.verifyData[0]++ 2217 } 2218 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...) 2219 hs.finishedBytes = finished.marshal() 2220 hs.writeServerHash(hs.finishedBytes) 2221 postCCSBytes := hs.finishedBytes 2222 if c.config.Bugs.PartialFinishedWithServerHelloDone { 2223 // The first byte has already been sent. 2224 postCCSBytes = postCCSBytes[1:] 2225 } 2226 2227 if c.config.Bugs.FragmentAcrossChangeCipherSpec { 2228 c.writeRecord(recordTypeHandshake, postCCSBytes[:5]) 2229 postCCSBytes = postCCSBytes[5:] 2230 } else if c.config.Bugs.SendUnencryptedFinished { 2231 c.writeRecord(recordTypeHandshake, postCCSBytes) 2232 postCCSBytes = nil 2233 } 2234 2235 if !c.config.Bugs.SkipChangeCipherSpec { 2236 ccs := []byte{1} 2237 if c.config.Bugs.BadChangeCipherSpec != nil { 2238 ccs = c.config.Bugs.BadChangeCipherSpec 2239 } 2240 c.writeRecord(recordTypeChangeCipherSpec, ccs) 2241 } 2242 2243 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil { 2244 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec) 2245 } 2246 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 { 2247 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec) 2248 return errors.New("tls: simulating post-CCS alert") 2249 } 2250 2251 if !c.config.Bugs.SkipFinished && len(postCCSBytes) > 0 { 2252 c.writeRecord(recordTypeHandshake, postCCSBytes) 2253 if c.config.Bugs.SendExtraFinished { 2254 c.writeRecord(recordTypeHandshake, finished.marshal()) 2255 } 2256 } 2257 2258 if isResume || (!c.config.Bugs.PackHelloRequestWithFinished && !c.config.Bugs.PackAppDataWithHandshake) { 2259 // Defer flushing until Renegotiate() or Write(). 2260 c.flushHandshake() 2261 } 2262 2263 c.cipherSuite = hs.suite 2264 2265 return nil 2266} 2267 2268// processCertsFromClient takes a chain of client certificates either from a 2269// Certificates message or from a sessionState and verifies them. It returns 2270// the public key of the leaf certificate. 2271func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) { 2272 c := hs.c 2273 2274 hs.certsFromClient = certificates 2275 certs := make([]*x509.Certificate, len(certificates)) 2276 var err error 2277 for i, asn1Data := range certificates { 2278 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil { 2279 c.sendAlert(alertBadCertificate) 2280 return nil, errors.New("tls: failed to parse client certificate: " + err.Error()) 2281 } 2282 } 2283 2284 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 { 2285 opts := x509.VerifyOptions{ 2286 Roots: c.config.ClientCAs, 2287 CurrentTime: c.config.time(), 2288 Intermediates: x509.NewCertPool(), 2289 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, 2290 } 2291 2292 for _, cert := range certs[1:] { 2293 opts.Intermediates.AddCert(cert) 2294 } 2295 2296 chains, err := certs[0].Verify(opts) 2297 if err != nil { 2298 c.sendAlert(alertBadCertificate) 2299 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error()) 2300 } 2301 2302 ok := false 2303 for _, ku := range certs[0].ExtKeyUsage { 2304 if ku == x509.ExtKeyUsageClientAuth { 2305 ok = true 2306 break 2307 } 2308 } 2309 if !ok { 2310 c.sendAlert(alertHandshakeFailure) 2311 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication") 2312 } 2313 2314 c.verifiedChains = chains 2315 } 2316 2317 if len(certs) > 0 { 2318 pub := certs[0].PublicKey 2319 switch pub.(type) { 2320 case *ecdsa.PublicKey, *rsa.PublicKey, ed25519.PublicKey: 2321 break 2322 default: 2323 c.sendAlert(alertUnsupportedCertificate) 2324 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", pub) 2325 } 2326 c.peerCertificates = certs 2327 return pub, nil 2328 } 2329 2330 return nil, nil 2331} 2332 2333func verifyChannelIDMessage(channelIDMsg *channelIDMsg, channelIDHash []byte) (*ecdsa.PublicKey, error) { 2334 x := new(big.Int).SetBytes(channelIDMsg.channelID[0:32]) 2335 y := new(big.Int).SetBytes(channelIDMsg.channelID[32:64]) 2336 r := new(big.Int).SetBytes(channelIDMsg.channelID[64:96]) 2337 s := new(big.Int).SetBytes(channelIDMsg.channelID[96:128]) 2338 if !elliptic.P256().IsOnCurve(x, y) { 2339 return nil, errors.New("tls: invalid channel ID public key") 2340 } 2341 channelID := &ecdsa.PublicKey{Curve: elliptic.P256(), X: x, Y: y} 2342 if !ecdsa.Verify(channelID, channelIDHash, r, s) { 2343 return nil, errors.New("tls: invalid channel ID signature") 2344 } 2345 return channelID, nil 2346} 2347 2348func (hs *serverHandshakeState) writeServerHash(msg []byte) { 2349 // writeServerHash is called before writeRecord. 2350 hs.finishedHash.WriteHandshake(msg, hs.c.sendHandshakeSeq) 2351} 2352 2353func (hs *serverHandshakeState) writeClientHash(msg []byte) { 2354 // writeClientHash is called after readHandshake. 2355 hs.finishedHash.WriteHandshake(msg, hs.c.recvHandshakeSeq-1) 2356} 2357 2358// tryCipherSuite returns a cipherSuite with the given id if that cipher suite 2359// is acceptable to use. 2360func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite { 2361 for _, supported := range supportedCipherSuites { 2362 if id == supported { 2363 var candidate *cipherSuite 2364 2365 for _, s := range cipherSuites { 2366 if s.id == id { 2367 candidate = s 2368 break 2369 } 2370 } 2371 if candidate == nil { 2372 continue 2373 } 2374 2375 // Don't select a ciphersuite which we can't 2376 // support for this client. 2377 if version >= VersionTLS13 || candidate.flags&suiteTLS13 != 0 { 2378 if version < VersionTLS13 || candidate.flags&suiteTLS13 == 0 { 2379 continue 2380 } 2381 return candidate 2382 } 2383 if (candidate.flags&suiteECDHE != 0) && !ellipticOk { 2384 continue 2385 } 2386 if (candidate.flags&suiteECDSA != 0) != ecdsaOk { 2387 continue 2388 } 2389 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 { 2390 continue 2391 } 2392 return candidate 2393 } 2394 } 2395 2396 return nil 2397} 2398 2399func isTLS12Cipher(id uint16) bool { 2400 for _, cipher := range cipherSuites { 2401 if cipher.id != id { 2402 continue 2403 } 2404 return cipher.flags&suiteTLS12 != 0 2405 } 2406 // Unknown cipher. 2407 return false 2408} 2409 2410func isGREASEValue(val uint16) bool { 2411 return val&0x0f0f == 0x0a0a && val&0xff == val>>8 2412} 2413 2414func verifyPSKBinder(version uint16, clientHello *clientHelloMsg, sessionState *sessionState, binderToVerify, firstClientHello, helloRetryRequest []byte) error { 2415 binderLen := 2 2416 for _, binder := range clientHello.pskBinders { 2417 binderLen += 1 + len(binder) 2418 } 2419 2420 truncatedHello := clientHello.marshal() 2421 truncatedHello = truncatedHello[:len(truncatedHello)-binderLen] 2422 pskCipherSuite := cipherSuiteFromID(sessionState.cipherSuite) 2423 if pskCipherSuite == nil { 2424 return errors.New("tls: Unknown cipher suite for PSK in session") 2425 } 2426 2427 binder := computePSKBinder(sessionState.secret, version, resumptionPSKBinderLabel, pskCipherSuite, firstClientHello, helloRetryRequest, truncatedHello) 2428 if !bytes.Equal(binder, binderToVerify) { 2429 return errors.New("tls: PSK binder does not verify") 2430 } 2431 2432 return nil 2433} 2434 2435// checkClientHellosEqual checks whether a and b are equal ClientHello 2436// messages. If isDTLS is true, the ClientHellos are parsed as DTLS and any 2437// differences in the cookie field are ignored. Extensions listed in 2438// ignoreExtensions may change or be removed between the two ClientHellos. 2439func checkClientHellosEqual(a, b []byte, isDTLS bool, ignoreExtensions []uint16) error { 2440 ignoreExtensionsSet := make(map[uint16]struct{}) 2441 for _, ext := range ignoreExtensions { 2442 ignoreExtensionsSet[ext] = struct{}{} 2443 } 2444 2445 // Skip the handshake message header. 2446 aReader := byteReader(a[4:]) 2447 bReader := byteReader(b[4:]) 2448 2449 var aVers, bVers uint16 2450 var aRandom, bRandom []byte 2451 var aSessionID, bSessionID []byte 2452 if !aReader.readU16(&aVers) || 2453 !bReader.readU16(&bVers) || 2454 !aReader.readBytes(&aRandom, 32) || 2455 !bReader.readBytes(&bRandom, 32) || 2456 !aReader.readU8LengthPrefixedBytes(&aSessionID) || 2457 !bReader.readU8LengthPrefixedBytes(&bSessionID) { 2458 return errors.New("tls: could not parse ClientHello") 2459 } 2460 2461 if aVers != bVers { 2462 return errors.New("tls: second ClientHello version did not match") 2463 } 2464 if !bytes.Equal(aRandom, bRandom) { 2465 return errors.New("tls: second ClientHello random did not match") 2466 } 2467 if !bytes.Equal(aSessionID, bSessionID) { 2468 return errors.New("tls: second ClientHello session ID did not match") 2469 } 2470 2471 if isDTLS { 2472 // DTLS 1.2 checks two ClientHellos match after a HelloVerifyRequest, 2473 // where we expect the cookies to change. DTLS 1.3 forbids the legacy 2474 // cookie altogether. If we implement DTLS 1.3, we'll need to ensure 2475 // that parsing logic above this function rejects this cookie. 2476 var aCookie, bCookie []byte 2477 if !aReader.readU8LengthPrefixedBytes(&aCookie) || 2478 !bReader.readU8LengthPrefixedBytes(&bCookie) { 2479 return errors.New("tls: could not parse ClientHello") 2480 } 2481 } 2482 2483 var aCipherSuites, bCipherSuites, aCompressionMethods, bCompressionMethods []byte 2484 if !aReader.readU16LengthPrefixedBytes(&aCipherSuites) || 2485 !bReader.readU16LengthPrefixedBytes(&bCipherSuites) || 2486 !aReader.readU8LengthPrefixedBytes(&aCompressionMethods) || 2487 !bReader.readU8LengthPrefixedBytes(&bCompressionMethods) { 2488 return errors.New("tls: could not parse ClientHello") 2489 } 2490 if !bytes.Equal(aCipherSuites, bCipherSuites) { 2491 return errors.New("tls: second ClientHello cipher suites did not match") 2492 } 2493 if !bytes.Equal(aCompressionMethods, bCompressionMethods) { 2494 return errors.New("tls: second ClientHello compression methods did not match") 2495 } 2496 2497 if len(aReader) == 0 && len(bReader) == 0 { 2498 // Both ClientHellos omit the extensions block. 2499 return nil 2500 } 2501 2502 var aExtensions, bExtensions byteReader 2503 if !aReader.readU16LengthPrefixed(&aExtensions) || 2504 !bReader.readU16LengthPrefixed(&bExtensions) || 2505 len(aReader) != 0 || 2506 len(bReader) != 0 { 2507 return errors.New("tls: could not parse ClientHello") 2508 } 2509 2510 for len(aExtensions) != 0 { 2511 var aID uint16 2512 var aBody []byte 2513 if !aExtensions.readU16(&aID) || 2514 !aExtensions.readU16LengthPrefixedBytes(&aBody) { 2515 return errors.New("tls: could not parse ClientHello") 2516 } 2517 if _, ok := ignoreExtensionsSet[aID]; ok { 2518 continue 2519 } 2520 2521 for { 2522 if len(bExtensions) == 0 { 2523 return fmt.Errorf("tls: second ClientHello missing extension %d", aID) 2524 } 2525 var bID uint16 2526 var bBody []byte 2527 if !bExtensions.readU16(&bID) || 2528 !bExtensions.readU16LengthPrefixedBytes(&bBody) { 2529 return errors.New("tls: could not parse ClientHello") 2530 } 2531 if _, ok := ignoreExtensionsSet[bID]; ok { 2532 continue 2533 } 2534 if aID != bID { 2535 return fmt.Errorf("tls: unexpected extension %d in second ClientHello (wanted %d)", bID, aID) 2536 } 2537 if !bytes.Equal(aBody, bBody) { 2538 return fmt.Errorf("tls: extension %d in second ClientHello unexpectedly changed", aID) 2539 } 2540 break 2541 } 2542 } 2543 2544 // Any remaining extensions in the second ClientHello must be in the 2545 // ignored set. 2546 for len(bExtensions) != 0 { 2547 var id uint16 2548 var body []byte 2549 if !bExtensions.readU16(&id) || 2550 !bExtensions.readU16LengthPrefixedBytes(&body) { 2551 return errors.New("tls: could not parse ClientHello") 2552 } 2553 if _, ok := ignoreExtensionsSet[id]; !ok { 2554 return fmt.Errorf("tls: unexpected extension %d in second ClientHello", id) 2555 } 2556 } 2557 2558 return nil 2559} 2560