github.com/twelsh-aw/go/src@v0.0.0-20230516233729-a56fe86a7c81/crypto/tls/handshake_server_tls13.go (about) 1 // Copyright 2018 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 5 package tls 6 7 import ( 8 "bytes" 9 "context" 10 "crypto" 11 "crypto/hmac" 12 "crypto/rsa" 13 "encoding/binary" 14 "errors" 15 "hash" 16 "io" 17 "time" 18 ) 19 20 // maxClientPSKIdentities is the number of client PSK identities the server will 21 // attempt to validate. It will ignore the rest not to let cheap ClientHello 22 // messages cause too much work in session ticket decryption attempts. 23 const maxClientPSKIdentities = 5 24 25 type serverHandshakeStateTLS13 struct { 26 c *Conn 27 ctx context.Context 28 clientHello *clientHelloMsg 29 hello *serverHelloMsg 30 sentDummyCCS bool 31 usingPSK bool 32 suite *cipherSuiteTLS13 33 cert *Certificate 34 sigAlg SignatureScheme 35 earlySecret []byte 36 sharedKey []byte 37 handshakeSecret []byte 38 masterSecret []byte 39 trafficSecret []byte // client_application_traffic_secret_0 40 transcript hash.Hash 41 clientFinished []byte 42 } 43 44 func (hs *serverHandshakeStateTLS13) handshake() error { 45 c := hs.c 46 47 if needFIPS() { 48 return errors.New("tls: internal error: TLS 1.3 reached in FIPS mode") 49 } 50 51 // For an overview of the TLS 1.3 handshake, see RFC 8446, Section 2. 52 if err := hs.processClientHello(); err != nil { 53 return err 54 } 55 if err := hs.checkForResumption(); err != nil { 56 return err 57 } 58 if err := hs.pickCertificate(); err != nil { 59 return err 60 } 61 c.buffering = true 62 if err := hs.sendServerParameters(); err != nil { 63 return err 64 } 65 if err := hs.sendServerCertificate(); err != nil { 66 return err 67 } 68 if err := hs.sendServerFinished(); err != nil { 69 return err 70 } 71 // Note that at this point we could start sending application data without 72 // waiting for the client's second flight, but the application might not 73 // expect the lack of replay protection of the ClientHello parameters. 74 if _, err := c.flush(); err != nil { 75 return err 76 } 77 if err := hs.readClientCertificate(); err != nil { 78 return err 79 } 80 if err := hs.readClientFinished(); err != nil { 81 return err 82 } 83 84 c.isHandshakeComplete.Store(true) 85 86 return nil 87 } 88 89 func (hs *serverHandshakeStateTLS13) processClientHello() error { 90 c := hs.c 91 92 hs.hello = new(serverHelloMsg) 93 94 // TLS 1.3 froze the ServerHello.legacy_version field, and uses 95 // supported_versions instead. See RFC 8446, sections 4.1.3 and 4.2.1. 96 hs.hello.vers = VersionTLS12 97 hs.hello.supportedVersion = c.vers 98 99 if len(hs.clientHello.supportedVersions) == 0 { 100 c.sendAlert(alertIllegalParameter) 101 return errors.New("tls: client used the legacy version field to negotiate TLS 1.3") 102 } 103 104 // Abort if the client is doing a fallback and landing lower than what we 105 // support. See RFC 7507, which however does not specify the interaction 106 // with supported_versions. The only difference is that with 107 // supported_versions a client has a chance to attempt a [TLS 1.2, TLS 1.4] 108 // handshake in case TLS 1.3 is broken but 1.2 is not. Alas, in that case, 109 // it will have to drop the TLS_FALLBACK_SCSV protection if it falls back to 110 // TLS 1.2, because a TLS 1.3 server would abort here. The situation before 111 // supported_versions was not better because there was just no way to do a 112 // TLS 1.4 handshake without risking the server selecting TLS 1.3. 113 for _, id := range hs.clientHello.cipherSuites { 114 if id == TLS_FALLBACK_SCSV { 115 // Use c.vers instead of max(supported_versions) because an attacker 116 // could defeat this by adding an arbitrary high version otherwise. 117 if c.vers < c.config.maxSupportedVersion(roleServer) { 118 c.sendAlert(alertInappropriateFallback) 119 return errors.New("tls: client using inappropriate protocol fallback") 120 } 121 break 122 } 123 } 124 125 if len(hs.clientHello.compressionMethods) != 1 || 126 hs.clientHello.compressionMethods[0] != compressionNone { 127 c.sendAlert(alertIllegalParameter) 128 return errors.New("tls: TLS 1.3 client supports illegal compression methods") 129 } 130 131 hs.hello.random = make([]byte, 32) 132 if _, err := io.ReadFull(c.config.rand(), hs.hello.random); err != nil { 133 c.sendAlert(alertInternalError) 134 return err 135 } 136 137 if len(hs.clientHello.secureRenegotiation) != 0 { 138 c.sendAlert(alertHandshakeFailure) 139 return errors.New("tls: initial handshake had non-empty renegotiation extension") 140 } 141 142 if hs.clientHello.earlyData { 143 // See RFC 8446, Section 4.2.10 for the complicated behavior required 144 // here. The scenario is that a different server at our address offered 145 // to accept early data in the past, which we can't handle. For now, all 146 // 0-RTT enabled session tickets need to expire before a Go server can 147 // replace a server or join a pool. That's the same requirement that 148 // applies to mixing or replacing with any TLS 1.2 server. 149 c.sendAlert(alertUnsupportedExtension) 150 return errors.New("tls: client sent unexpected early data") 151 } 152 153 hs.hello.sessionId = hs.clientHello.sessionId 154 hs.hello.compressionMethod = compressionNone 155 156 preferenceList := defaultCipherSuitesTLS13 157 if !hasAESGCMHardwareSupport || !aesgcmPreferred(hs.clientHello.cipherSuites) { 158 preferenceList = defaultCipherSuitesTLS13NoAES 159 } 160 for _, suiteID := range preferenceList { 161 hs.suite = mutualCipherSuiteTLS13(hs.clientHello.cipherSuites, suiteID) 162 if hs.suite != nil { 163 break 164 } 165 } 166 if hs.suite == nil { 167 c.sendAlert(alertHandshakeFailure) 168 return errors.New("tls: no cipher suite supported by both client and server") 169 } 170 c.cipherSuite = hs.suite.id 171 hs.hello.cipherSuite = hs.suite.id 172 hs.transcript = hs.suite.hash.New() 173 174 // Pick the ECDHE group in server preference order, but give priority to 175 // groups with a key share, to avoid a HelloRetryRequest round-trip. 176 var selectedGroup CurveID 177 var clientKeyShare *keyShare 178 GroupSelection: 179 for _, preferredGroup := range c.config.curvePreferences() { 180 for _, ks := range hs.clientHello.keyShares { 181 if ks.group == preferredGroup { 182 selectedGroup = ks.group 183 clientKeyShare = &ks 184 break GroupSelection 185 } 186 } 187 if selectedGroup != 0 { 188 continue 189 } 190 for _, group := range hs.clientHello.supportedCurves { 191 if group == preferredGroup { 192 selectedGroup = group 193 break 194 } 195 } 196 } 197 if selectedGroup == 0 { 198 c.sendAlert(alertHandshakeFailure) 199 return errors.New("tls: no ECDHE curve supported by both client and server") 200 } 201 if clientKeyShare == nil { 202 if err := hs.doHelloRetryRequest(selectedGroup); err != nil { 203 return err 204 } 205 clientKeyShare = &hs.clientHello.keyShares[0] 206 } 207 208 if _, ok := curveForCurveID(selectedGroup); !ok { 209 c.sendAlert(alertInternalError) 210 return errors.New("tls: CurvePreferences includes unsupported curve") 211 } 212 key, err := generateECDHEKey(c.config.rand(), selectedGroup) 213 if err != nil { 214 c.sendAlert(alertInternalError) 215 return err 216 } 217 hs.hello.serverShare = keyShare{group: selectedGroup, data: key.PublicKey().Bytes()} 218 peerKey, err := key.Curve().NewPublicKey(clientKeyShare.data) 219 if err != nil { 220 c.sendAlert(alertIllegalParameter) 221 return errors.New("tls: invalid client key share") 222 } 223 hs.sharedKey, err = key.ECDH(peerKey) 224 if err != nil { 225 c.sendAlert(alertIllegalParameter) 226 return errors.New("tls: invalid client key share") 227 } 228 229 c.serverName = hs.clientHello.serverName 230 return nil 231 } 232 233 func (hs *serverHandshakeStateTLS13) checkForResumption() error { 234 c := hs.c 235 236 if c.config.SessionTicketsDisabled { 237 return nil 238 } 239 240 modeOK := false 241 for _, mode := range hs.clientHello.pskModes { 242 if mode == pskModeDHE { 243 modeOK = true 244 break 245 } 246 } 247 if !modeOK { 248 return nil 249 } 250 251 if len(hs.clientHello.pskIdentities) != len(hs.clientHello.pskBinders) { 252 c.sendAlert(alertIllegalParameter) 253 return errors.New("tls: invalid or missing PSK binders") 254 } 255 if len(hs.clientHello.pskIdentities) == 0 { 256 return nil 257 } 258 259 for i, identity := range hs.clientHello.pskIdentities { 260 if i >= maxClientPSKIdentities { 261 break 262 } 263 264 plaintext, _ := c.decryptTicket(identity.label) 265 if plaintext == nil { 266 continue 267 } 268 sessionState := new(sessionStateTLS13) 269 if ok := sessionState.unmarshal(plaintext); !ok { 270 continue 271 } 272 273 createdAt := time.Unix(int64(sessionState.createdAt), 0) 274 if c.config.time().Sub(createdAt) > maxSessionTicketLifetime { 275 continue 276 } 277 278 // We don't check the obfuscated ticket age because it's affected by 279 // clock skew and it's only a freshness signal useful for shrinking the 280 // window for replay attacks, which don't affect us as we don't do 0-RTT. 281 282 pskSuite := cipherSuiteTLS13ByID(sessionState.cipherSuite) 283 if pskSuite == nil || pskSuite.hash != hs.suite.hash { 284 continue 285 } 286 287 // PSK connections don't re-establish client certificates, but carry 288 // them over in the session ticket. Ensure the presence of client certs 289 // in the ticket is consistent with the configured requirements. 290 sessionHasClientCerts := len(sessionState.certificate.Certificate) != 0 291 needClientCerts := requiresClientCert(c.config.ClientAuth) 292 if needClientCerts && !sessionHasClientCerts { 293 continue 294 } 295 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert { 296 continue 297 } 298 299 psk := hs.suite.expandLabel(sessionState.resumptionSecret, "resumption", 300 nil, hs.suite.hash.Size()) 301 hs.earlySecret = hs.suite.extract(psk, nil) 302 binderKey := hs.suite.deriveSecret(hs.earlySecret, resumptionBinderLabel, nil) 303 // Clone the transcript in case a HelloRetryRequest was recorded. 304 transcript := cloneHash(hs.transcript, hs.suite.hash) 305 if transcript == nil { 306 c.sendAlert(alertInternalError) 307 return errors.New("tls: internal error: failed to clone hash") 308 } 309 clientHelloBytes, err := hs.clientHello.marshalWithoutBinders() 310 if err != nil { 311 c.sendAlert(alertInternalError) 312 return err 313 } 314 transcript.Write(clientHelloBytes) 315 pskBinder := hs.suite.finishedHash(binderKey, transcript) 316 if !hmac.Equal(hs.clientHello.pskBinders[i], pskBinder) { 317 c.sendAlert(alertDecryptError) 318 return errors.New("tls: invalid PSK binder") 319 } 320 321 c.didResume = true 322 if err := c.processCertsFromClient(sessionState.certificate); err != nil { 323 return err 324 } 325 326 hs.hello.selectedIdentityPresent = true 327 hs.hello.selectedIdentity = uint16(i) 328 hs.usingPSK = true 329 return nil 330 } 331 332 return nil 333 } 334 335 // cloneHash uses the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler 336 // interfaces implemented by standard library hashes to clone the state of in 337 // to a new instance of h. It returns nil if the operation fails. 338 func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash { 339 // Recreate the interface to avoid importing encoding. 340 type binaryMarshaler interface { 341 MarshalBinary() (data []byte, err error) 342 UnmarshalBinary(data []byte) error 343 } 344 marshaler, ok := in.(binaryMarshaler) 345 if !ok { 346 return nil 347 } 348 state, err := marshaler.MarshalBinary() 349 if err != nil { 350 return nil 351 } 352 out := h.New() 353 unmarshaler, ok := out.(binaryMarshaler) 354 if !ok { 355 return nil 356 } 357 if err := unmarshaler.UnmarshalBinary(state); err != nil { 358 return nil 359 } 360 return out 361 } 362 363 func (hs *serverHandshakeStateTLS13) pickCertificate() error { 364 c := hs.c 365 366 // Only one of PSK and certificates are used at a time. 367 if hs.usingPSK { 368 return nil 369 } 370 371 // signature_algorithms is required in TLS 1.3. See RFC 8446, Section 4.2.3. 372 if len(hs.clientHello.supportedSignatureAlgorithms) == 0 { 373 return c.sendAlert(alertMissingExtension) 374 } 375 376 certificate, err := c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello)) 377 if err != nil { 378 if err == errNoCertificates { 379 c.sendAlert(alertUnrecognizedName) 380 } else { 381 c.sendAlert(alertInternalError) 382 } 383 return err 384 } 385 hs.sigAlg, err = selectSignatureScheme(c.vers, certificate, hs.clientHello.supportedSignatureAlgorithms) 386 if err != nil { 387 // getCertificate returned a certificate that is unsupported or 388 // incompatible with the client's signature algorithms. 389 c.sendAlert(alertHandshakeFailure) 390 return err 391 } 392 hs.cert = certificate 393 394 return nil 395 } 396 397 // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility 398 // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4. 399 func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error { 400 if hs.sentDummyCCS { 401 return nil 402 } 403 hs.sentDummyCCS = true 404 405 return hs.c.writeChangeCipherRecord() 406 } 407 408 func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) error { 409 c := hs.c 410 411 // The first ClientHello gets double-hashed into the transcript upon a 412 // HelloRetryRequest. See RFC 8446, Section 4.4.1. 413 if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil { 414 return err 415 } 416 chHash := hs.transcript.Sum(nil) 417 hs.transcript.Reset() 418 hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))}) 419 hs.transcript.Write(chHash) 420 421 helloRetryRequest := &serverHelloMsg{ 422 vers: hs.hello.vers, 423 random: helloRetryRequestRandom, 424 sessionId: hs.hello.sessionId, 425 cipherSuite: hs.hello.cipherSuite, 426 compressionMethod: hs.hello.compressionMethod, 427 supportedVersion: hs.hello.supportedVersion, 428 selectedGroup: selectedGroup, 429 } 430 431 if _, err := hs.c.writeHandshakeRecord(helloRetryRequest, hs.transcript); err != nil { 432 return err 433 } 434 435 if err := hs.sendDummyChangeCipherSpec(); err != nil { 436 return err 437 } 438 439 // clientHelloMsg is not included in the transcript. 440 msg, err := c.readHandshake(nil) 441 if err != nil { 442 return err 443 } 444 445 clientHello, ok := msg.(*clientHelloMsg) 446 if !ok { 447 c.sendAlert(alertUnexpectedMessage) 448 return unexpectedMessageError(clientHello, msg) 449 } 450 451 if len(clientHello.keyShares) != 1 || clientHello.keyShares[0].group != selectedGroup { 452 c.sendAlert(alertIllegalParameter) 453 return errors.New("tls: client sent invalid key share in second ClientHello") 454 } 455 456 if clientHello.earlyData { 457 c.sendAlert(alertIllegalParameter) 458 return errors.New("tls: client indicated early data in second ClientHello") 459 } 460 461 if illegalClientHelloChange(clientHello, hs.clientHello) { 462 c.sendAlert(alertIllegalParameter) 463 return errors.New("tls: client illegally modified second ClientHello") 464 } 465 466 hs.clientHello = clientHello 467 return nil 468 } 469 470 // illegalClientHelloChange reports whether the two ClientHello messages are 471 // different, with the exception of the changes allowed before and after a 472 // HelloRetryRequest. See RFC 8446, Section 4.1.2. 473 func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool { 474 if len(ch.supportedVersions) != len(ch1.supportedVersions) || 475 len(ch.cipherSuites) != len(ch1.cipherSuites) || 476 len(ch.supportedCurves) != len(ch1.supportedCurves) || 477 len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) || 478 len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) || 479 len(ch.alpnProtocols) != len(ch1.alpnProtocols) { 480 return true 481 } 482 for i := range ch.supportedVersions { 483 if ch.supportedVersions[i] != ch1.supportedVersions[i] { 484 return true 485 } 486 } 487 for i := range ch.cipherSuites { 488 if ch.cipherSuites[i] != ch1.cipherSuites[i] { 489 return true 490 } 491 } 492 for i := range ch.supportedCurves { 493 if ch.supportedCurves[i] != ch1.supportedCurves[i] { 494 return true 495 } 496 } 497 for i := range ch.supportedSignatureAlgorithms { 498 if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] { 499 return true 500 } 501 } 502 for i := range ch.supportedSignatureAlgorithmsCert { 503 if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] { 504 return true 505 } 506 } 507 for i := range ch.alpnProtocols { 508 if ch.alpnProtocols[i] != ch1.alpnProtocols[i] { 509 return true 510 } 511 } 512 return ch.vers != ch1.vers || 513 !bytes.Equal(ch.random, ch1.random) || 514 !bytes.Equal(ch.sessionId, ch1.sessionId) || 515 !bytes.Equal(ch.compressionMethods, ch1.compressionMethods) || 516 ch.serverName != ch1.serverName || 517 ch.ocspStapling != ch1.ocspStapling || 518 !bytes.Equal(ch.supportedPoints, ch1.supportedPoints) || 519 ch.ticketSupported != ch1.ticketSupported || 520 !bytes.Equal(ch.sessionTicket, ch1.sessionTicket) || 521 ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported || 522 !bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) || 523 ch.scts != ch1.scts || 524 !bytes.Equal(ch.cookie, ch1.cookie) || 525 !bytes.Equal(ch.pskModes, ch1.pskModes) 526 } 527 528 func (hs *serverHandshakeStateTLS13) sendServerParameters() error { 529 c := hs.c 530 531 if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil { 532 return err 533 } 534 if _, err := hs.c.writeHandshakeRecord(hs.hello, hs.transcript); err != nil { 535 return err 536 } 537 538 if err := hs.sendDummyChangeCipherSpec(); err != nil { 539 return err 540 } 541 542 earlySecret := hs.earlySecret 543 if earlySecret == nil { 544 earlySecret = hs.suite.extract(nil, nil) 545 } 546 hs.handshakeSecret = hs.suite.extract(hs.sharedKey, 547 hs.suite.deriveSecret(earlySecret, "derived", nil)) 548 549 clientSecret := hs.suite.deriveSecret(hs.handshakeSecret, 550 clientHandshakeTrafficLabel, hs.transcript) 551 c.in.setTrafficSecret(hs.suite, clientSecret) 552 serverSecret := hs.suite.deriveSecret(hs.handshakeSecret, 553 serverHandshakeTrafficLabel, hs.transcript) 554 c.out.setTrafficSecret(hs.suite, serverSecret) 555 556 err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret) 557 if err != nil { 558 c.sendAlert(alertInternalError) 559 return err 560 } 561 err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret) 562 if err != nil { 563 c.sendAlert(alertInternalError) 564 return err 565 } 566 567 encryptedExtensions := new(encryptedExtensionsMsg) 568 569 selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols) 570 if err != nil { 571 c.sendAlert(alertNoApplicationProtocol) 572 return err 573 } 574 encryptedExtensions.alpnProtocol = selectedProto 575 c.clientProtocol = selectedProto 576 577 if _, err := hs.c.writeHandshakeRecord(encryptedExtensions, hs.transcript); err != nil { 578 return err 579 } 580 581 return nil 582 } 583 584 func (hs *serverHandshakeStateTLS13) requestClientCert() bool { 585 return hs.c.config.ClientAuth >= RequestClientCert && !hs.usingPSK 586 } 587 588 func (hs *serverHandshakeStateTLS13) sendServerCertificate() error { 589 c := hs.c 590 591 // Only one of PSK and certificates are used at a time. 592 if hs.usingPSK { 593 return nil 594 } 595 596 if hs.requestClientCert() { 597 // Request a client certificate 598 certReq := new(certificateRequestMsgTLS13) 599 certReq.ocspStapling = true 600 certReq.scts = true 601 certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms() 602 if c.config.ClientCAs != nil { 603 certReq.certificateAuthorities = c.config.ClientCAs.Subjects() 604 } 605 606 if _, err := hs.c.writeHandshakeRecord(certReq, hs.transcript); err != nil { 607 return err 608 } 609 } 610 611 certMsg := new(certificateMsgTLS13) 612 613 certMsg.certificate = *hs.cert 614 certMsg.scts = hs.clientHello.scts && len(hs.cert.SignedCertificateTimestamps) > 0 615 certMsg.ocspStapling = hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 616 617 if _, err := hs.c.writeHandshakeRecord(certMsg, hs.transcript); err != nil { 618 return err 619 } 620 621 certVerifyMsg := new(certificateVerifyMsg) 622 certVerifyMsg.hasSignatureAlgorithm = true 623 certVerifyMsg.signatureAlgorithm = hs.sigAlg 624 625 sigType, sigHash, err := typeAndHashFromSignatureScheme(hs.sigAlg) 626 if err != nil { 627 return c.sendAlert(alertInternalError) 628 } 629 630 signed := signedMessage(sigHash, serverSignatureContext, hs.transcript) 631 signOpts := crypto.SignerOpts(sigHash) 632 if sigType == signatureRSAPSS { 633 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash} 634 } 635 sig, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts) 636 if err != nil { 637 public := hs.cert.PrivateKey.(crypto.Signer).Public() 638 if rsaKey, ok := public.(*rsa.PublicKey); ok && sigType == signatureRSAPSS && 639 rsaKey.N.BitLen()/8 < sigHash.Size()*2+2 { // key too small for RSA-PSS 640 c.sendAlert(alertHandshakeFailure) 641 } else { 642 c.sendAlert(alertInternalError) 643 } 644 return errors.New("tls: failed to sign handshake: " + err.Error()) 645 } 646 certVerifyMsg.signature = sig 647 648 if _, err := hs.c.writeHandshakeRecord(certVerifyMsg, hs.transcript); err != nil { 649 return err 650 } 651 652 return nil 653 } 654 655 func (hs *serverHandshakeStateTLS13) sendServerFinished() error { 656 c := hs.c 657 658 finished := &finishedMsg{ 659 verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript), 660 } 661 662 if _, err := hs.c.writeHandshakeRecord(finished, hs.transcript); err != nil { 663 return err 664 } 665 666 // Derive secrets that take context through the server Finished. 667 668 hs.masterSecret = hs.suite.extract(nil, 669 hs.suite.deriveSecret(hs.handshakeSecret, "derived", nil)) 670 671 hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret, 672 clientApplicationTrafficLabel, hs.transcript) 673 serverSecret := hs.suite.deriveSecret(hs.masterSecret, 674 serverApplicationTrafficLabel, hs.transcript) 675 c.out.setTrafficSecret(hs.suite, serverSecret) 676 677 err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret) 678 if err != nil { 679 c.sendAlert(alertInternalError) 680 return err 681 } 682 err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.clientHello.random, serverSecret) 683 if err != nil { 684 c.sendAlert(alertInternalError) 685 return err 686 } 687 688 c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript) 689 690 // If we did not request client certificates, at this point we can 691 // precompute the client finished and roll the transcript forward to send 692 // session tickets in our first flight. 693 if !hs.requestClientCert() { 694 if err := hs.sendSessionTickets(); err != nil { 695 return err 696 } 697 } 698 699 return nil 700 } 701 702 func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool { 703 if hs.c.config.SessionTicketsDisabled { 704 return false 705 } 706 707 // Don't send tickets the client wouldn't use. See RFC 8446, Section 4.2.9. 708 for _, pskMode := range hs.clientHello.pskModes { 709 if pskMode == pskModeDHE { 710 return true 711 } 712 } 713 return false 714 } 715 716 func (hs *serverHandshakeStateTLS13) sendSessionTickets() error { 717 c := hs.c 718 719 hs.clientFinished = hs.suite.finishedHash(c.in.trafficSecret, hs.transcript) 720 finishedMsg := &finishedMsg{ 721 verifyData: hs.clientFinished, 722 } 723 if err := transcriptMsg(finishedMsg, hs.transcript); err != nil { 724 return err 725 } 726 727 if !hs.shouldSendSessionTickets() { 728 return nil 729 } 730 731 resumptionSecret := hs.suite.deriveSecret(hs.masterSecret, 732 resumptionLabel, hs.transcript) 733 734 m := new(newSessionTicketMsgTLS13) 735 736 var certsFromClient [][]byte 737 for _, cert := range c.peerCertificates { 738 certsFromClient = append(certsFromClient, cert.Raw) 739 } 740 state := sessionStateTLS13{ 741 cipherSuite: hs.suite.id, 742 createdAt: uint64(c.config.time().Unix()), 743 resumptionSecret: resumptionSecret, 744 certificate: Certificate{ 745 Certificate: certsFromClient, 746 OCSPStaple: c.ocspResponse, 747 SignedCertificateTimestamps: c.scts, 748 }, 749 } 750 stateBytes, err := state.marshal() 751 if err != nil { 752 c.sendAlert(alertInternalError) 753 return err 754 } 755 m.label, err = c.encryptTicket(stateBytes) 756 if err != nil { 757 return err 758 } 759 m.lifetime = uint32(maxSessionTicketLifetime / time.Second) 760 761 // ticket_age_add is a random 32-bit value. See RFC 8446, section 4.6.1 762 // The value is not stored anywhere; we never need to check the ticket age 763 // because 0-RTT is not supported. 764 ageAdd := make([]byte, 4) 765 _, err = hs.c.config.rand().Read(ageAdd) 766 if err != nil { 767 return err 768 } 769 m.ageAdd = binary.LittleEndian.Uint32(ageAdd) 770 771 // ticket_nonce, which must be unique per connection, is always left at 772 // zero because we only ever send one ticket per connection. 773 774 if _, err := c.writeHandshakeRecord(m, nil); err != nil { 775 return err 776 } 777 778 return nil 779 } 780 781 func (hs *serverHandshakeStateTLS13) readClientCertificate() error { 782 c := hs.c 783 784 if !hs.requestClientCert() { 785 // Make sure the connection is still being verified whether or not 786 // the server requested a client certificate. 787 if c.config.VerifyConnection != nil { 788 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { 789 c.sendAlert(alertBadCertificate) 790 return err 791 } 792 } 793 return nil 794 } 795 796 // If we requested a client certificate, then the client must send a 797 // certificate message. If it's empty, no CertificateVerify is sent. 798 799 msg, err := c.readHandshake(hs.transcript) 800 if err != nil { 801 return err 802 } 803 804 certMsg, ok := msg.(*certificateMsgTLS13) 805 if !ok { 806 c.sendAlert(alertUnexpectedMessage) 807 return unexpectedMessageError(certMsg, msg) 808 } 809 810 if err := c.processCertsFromClient(certMsg.certificate); err != nil { 811 return err 812 } 813 814 if c.config.VerifyConnection != nil { 815 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { 816 c.sendAlert(alertBadCertificate) 817 return err 818 } 819 } 820 821 if len(certMsg.certificate.Certificate) != 0 { 822 // certificateVerifyMsg is included in the transcript, but not until 823 // after we verify the handshake signature, since the state before 824 // this message was sent is used. 825 msg, err = c.readHandshake(nil) 826 if err != nil { 827 return err 828 } 829 830 certVerify, ok := msg.(*certificateVerifyMsg) 831 if !ok { 832 c.sendAlert(alertUnexpectedMessage) 833 return unexpectedMessageError(certVerify, msg) 834 } 835 836 // See RFC 8446, Section 4.4.3. 837 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) { 838 c.sendAlert(alertIllegalParameter) 839 return errors.New("tls: client certificate used with invalid signature algorithm") 840 } 841 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm) 842 if err != nil { 843 return c.sendAlert(alertInternalError) 844 } 845 if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 { 846 c.sendAlert(alertIllegalParameter) 847 return errors.New("tls: client certificate used with invalid signature algorithm") 848 } 849 signed := signedMessage(sigHash, clientSignatureContext, hs.transcript) 850 if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey, 851 sigHash, signed, certVerify.signature); err != nil { 852 c.sendAlert(alertDecryptError) 853 return errors.New("tls: invalid signature by the client certificate: " + err.Error()) 854 } 855 856 if err := transcriptMsg(certVerify, hs.transcript); err != nil { 857 return err 858 } 859 } 860 861 // If we waited until the client certificates to send session tickets, we 862 // are ready to do it now. 863 if err := hs.sendSessionTickets(); err != nil { 864 return err 865 } 866 867 return nil 868 } 869 870 func (hs *serverHandshakeStateTLS13) readClientFinished() error { 871 c := hs.c 872 873 // finishedMsg is not included in the transcript. 874 msg, err := c.readHandshake(nil) 875 if err != nil { 876 return err 877 } 878 879 finished, ok := msg.(*finishedMsg) 880 if !ok { 881 c.sendAlert(alertUnexpectedMessage) 882 return unexpectedMessageError(finished, msg) 883 } 884 885 if !hmac.Equal(hs.clientFinished, finished.verifyData) { 886 c.sendAlert(alertDecryptError) 887 return errors.New("tls: invalid client finished hash") 888 } 889 890 c.in.setTrafficSecret(hs.suite, hs.trafficSecret) 891 892 return nil 893 }