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