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