github.com/mtsmfm/go/src@v0.0.0-20221020090648-44bdcb9f8fde/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.Curve().ECDH(key, 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 transcript.Write(hs.clientHello.marshalWithoutBinders()) 310 pskBinder := hs.suite.finishedHash(binderKey, transcript) 311 if !hmac.Equal(hs.clientHello.pskBinders[i], pskBinder) { 312 c.sendAlert(alertDecryptError) 313 return errors.New("tls: invalid PSK binder") 314 } 315 316 c.didResume = true 317 if err := c.processCertsFromClient(sessionState.certificate); err != nil { 318 return err 319 } 320 321 hs.hello.selectedIdentityPresent = true 322 hs.hello.selectedIdentity = uint16(i) 323 hs.usingPSK = true 324 return nil 325 } 326 327 return nil 328 } 329 330 // cloneHash uses the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler 331 // interfaces implemented by standard library hashes to clone the state of in 332 // to a new instance of h. It returns nil if the operation fails. 333 func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash { 334 // Recreate the interface to avoid importing encoding. 335 type binaryMarshaler interface { 336 MarshalBinary() (data []byte, err error) 337 UnmarshalBinary(data []byte) error 338 } 339 marshaler, ok := in.(binaryMarshaler) 340 if !ok { 341 return nil 342 } 343 state, err := marshaler.MarshalBinary() 344 if err != nil { 345 return nil 346 } 347 out := h.New() 348 unmarshaler, ok := out.(binaryMarshaler) 349 if !ok { 350 return nil 351 } 352 if err := unmarshaler.UnmarshalBinary(state); err != nil { 353 return nil 354 } 355 return out 356 } 357 358 func (hs *serverHandshakeStateTLS13) pickCertificate() error { 359 c := hs.c 360 361 // Only one of PSK and certificates are used at a time. 362 if hs.usingPSK { 363 return nil 364 } 365 366 // signature_algorithms is required in TLS 1.3. See RFC 8446, Section 4.2.3. 367 if len(hs.clientHello.supportedSignatureAlgorithms) == 0 { 368 return c.sendAlert(alertMissingExtension) 369 } 370 371 certificate, err := c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello)) 372 if err != nil { 373 if err == errNoCertificates { 374 c.sendAlert(alertUnrecognizedName) 375 } else { 376 c.sendAlert(alertInternalError) 377 } 378 return err 379 } 380 hs.sigAlg, err = selectSignatureScheme(c.vers, certificate, hs.clientHello.supportedSignatureAlgorithms) 381 if err != nil { 382 // getCertificate returned a certificate that is unsupported or 383 // incompatible with the client's signature algorithms. 384 c.sendAlert(alertHandshakeFailure) 385 return err 386 } 387 hs.cert = certificate 388 389 return nil 390 } 391 392 // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility 393 // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4. 394 func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error { 395 if hs.sentDummyCCS { 396 return nil 397 } 398 hs.sentDummyCCS = true 399 400 _, err := hs.c.writeRecord(recordTypeChangeCipherSpec, []byte{1}) 401 return err 402 } 403 404 func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) error { 405 c := hs.c 406 407 // The first ClientHello gets double-hashed into the transcript upon a 408 // HelloRetryRequest. See RFC 8446, Section 4.4.1. 409 hs.transcript.Write(hs.clientHello.marshal()) 410 chHash := hs.transcript.Sum(nil) 411 hs.transcript.Reset() 412 hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))}) 413 hs.transcript.Write(chHash) 414 415 helloRetryRequest := &serverHelloMsg{ 416 vers: hs.hello.vers, 417 random: helloRetryRequestRandom, 418 sessionId: hs.hello.sessionId, 419 cipherSuite: hs.hello.cipherSuite, 420 compressionMethod: hs.hello.compressionMethod, 421 supportedVersion: hs.hello.supportedVersion, 422 selectedGroup: selectedGroup, 423 } 424 425 hs.transcript.Write(helloRetryRequest.marshal()) 426 if _, err := c.writeRecord(recordTypeHandshake, helloRetryRequest.marshal()); err != nil { 427 return err 428 } 429 430 if err := hs.sendDummyChangeCipherSpec(); err != nil { 431 return err 432 } 433 434 msg, err := c.readHandshake() 435 if err != nil { 436 return err 437 } 438 439 clientHello, ok := msg.(*clientHelloMsg) 440 if !ok { 441 c.sendAlert(alertUnexpectedMessage) 442 return unexpectedMessageError(clientHello, msg) 443 } 444 445 if len(clientHello.keyShares) != 1 || clientHello.keyShares[0].group != selectedGroup { 446 c.sendAlert(alertIllegalParameter) 447 return errors.New("tls: client sent invalid key share in second ClientHello") 448 } 449 450 if clientHello.earlyData { 451 c.sendAlert(alertIllegalParameter) 452 return errors.New("tls: client indicated early data in second ClientHello") 453 } 454 455 if illegalClientHelloChange(clientHello, hs.clientHello) { 456 c.sendAlert(alertIllegalParameter) 457 return errors.New("tls: client illegally modified second ClientHello") 458 } 459 460 hs.clientHello = clientHello 461 return nil 462 } 463 464 // illegalClientHelloChange reports whether the two ClientHello messages are 465 // different, with the exception of the changes allowed before and after a 466 // HelloRetryRequest. See RFC 8446, Section 4.1.2. 467 func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool { 468 if len(ch.supportedVersions) != len(ch1.supportedVersions) || 469 len(ch.cipherSuites) != len(ch1.cipherSuites) || 470 len(ch.supportedCurves) != len(ch1.supportedCurves) || 471 len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) || 472 len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) || 473 len(ch.alpnProtocols) != len(ch1.alpnProtocols) { 474 return true 475 } 476 for i := range ch.supportedVersions { 477 if ch.supportedVersions[i] != ch1.supportedVersions[i] { 478 return true 479 } 480 } 481 for i := range ch.cipherSuites { 482 if ch.cipherSuites[i] != ch1.cipherSuites[i] { 483 return true 484 } 485 } 486 for i := range ch.supportedCurves { 487 if ch.supportedCurves[i] != ch1.supportedCurves[i] { 488 return true 489 } 490 } 491 for i := range ch.supportedSignatureAlgorithms { 492 if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] { 493 return true 494 } 495 } 496 for i := range ch.supportedSignatureAlgorithmsCert { 497 if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] { 498 return true 499 } 500 } 501 for i := range ch.alpnProtocols { 502 if ch.alpnProtocols[i] != ch1.alpnProtocols[i] { 503 return true 504 } 505 } 506 return ch.vers != ch1.vers || 507 !bytes.Equal(ch.random, ch1.random) || 508 !bytes.Equal(ch.sessionId, ch1.sessionId) || 509 !bytes.Equal(ch.compressionMethods, ch1.compressionMethods) || 510 ch.serverName != ch1.serverName || 511 ch.ocspStapling != ch1.ocspStapling || 512 !bytes.Equal(ch.supportedPoints, ch1.supportedPoints) || 513 ch.ticketSupported != ch1.ticketSupported || 514 !bytes.Equal(ch.sessionTicket, ch1.sessionTicket) || 515 ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported || 516 !bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) || 517 ch.scts != ch1.scts || 518 !bytes.Equal(ch.cookie, ch1.cookie) || 519 !bytes.Equal(ch.pskModes, ch1.pskModes) 520 } 521 522 func (hs *serverHandshakeStateTLS13) sendServerParameters() error { 523 c := hs.c 524 525 hs.transcript.Write(hs.clientHello.marshal()) 526 hs.transcript.Write(hs.hello.marshal()) 527 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil { 528 return err 529 } 530 531 if err := hs.sendDummyChangeCipherSpec(); err != nil { 532 return err 533 } 534 535 earlySecret := hs.earlySecret 536 if earlySecret == nil { 537 earlySecret = hs.suite.extract(nil, nil) 538 } 539 hs.handshakeSecret = hs.suite.extract(hs.sharedKey, 540 hs.suite.deriveSecret(earlySecret, "derived", nil)) 541 542 clientSecret := hs.suite.deriveSecret(hs.handshakeSecret, 543 clientHandshakeTrafficLabel, hs.transcript) 544 c.in.setTrafficSecret(hs.suite, clientSecret) 545 serverSecret := hs.suite.deriveSecret(hs.handshakeSecret, 546 serverHandshakeTrafficLabel, hs.transcript) 547 c.out.setTrafficSecret(hs.suite, serverSecret) 548 549 err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret) 550 if err != nil { 551 c.sendAlert(alertInternalError) 552 return err 553 } 554 err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret) 555 if err != nil { 556 c.sendAlert(alertInternalError) 557 return err 558 } 559 560 encryptedExtensions := new(encryptedExtensionsMsg) 561 562 selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols) 563 if err != nil { 564 c.sendAlert(alertNoApplicationProtocol) 565 return err 566 } 567 encryptedExtensions.alpnProtocol = selectedProto 568 c.clientProtocol = selectedProto 569 570 hs.transcript.Write(encryptedExtensions.marshal()) 571 if _, err := c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()); err != nil { 572 return err 573 } 574 575 return nil 576 } 577 578 func (hs *serverHandshakeStateTLS13) requestClientCert() bool { 579 return hs.c.config.ClientAuth >= RequestClientCert && !hs.usingPSK 580 } 581 582 func (hs *serverHandshakeStateTLS13) sendServerCertificate() error { 583 c := hs.c 584 585 // Only one of PSK and certificates are used at a time. 586 if hs.usingPSK { 587 return nil 588 } 589 590 if hs.requestClientCert() { 591 // Request a client certificate 592 certReq := new(certificateRequestMsgTLS13) 593 certReq.ocspStapling = true 594 certReq.scts = true 595 certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms() 596 if c.config.ClientCAs != nil { 597 certReq.certificateAuthorities = c.config.ClientCAs.Subjects() 598 } 599 600 hs.transcript.Write(certReq.marshal()) 601 if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil { 602 return err 603 } 604 } 605 606 certMsg := new(certificateMsgTLS13) 607 608 certMsg.certificate = *hs.cert 609 certMsg.scts = hs.clientHello.scts && len(hs.cert.SignedCertificateTimestamps) > 0 610 certMsg.ocspStapling = hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 611 612 hs.transcript.Write(certMsg.marshal()) 613 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil { 614 return err 615 } 616 617 certVerifyMsg := new(certificateVerifyMsg) 618 certVerifyMsg.hasSignatureAlgorithm = true 619 certVerifyMsg.signatureAlgorithm = hs.sigAlg 620 621 sigType, sigHash, err := typeAndHashFromSignatureScheme(hs.sigAlg) 622 if err != nil { 623 return c.sendAlert(alertInternalError) 624 } 625 626 signed := signedMessage(sigHash, serverSignatureContext, hs.transcript) 627 signOpts := crypto.SignerOpts(sigHash) 628 if sigType == signatureRSAPSS { 629 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash} 630 } 631 sig, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts) 632 if err != nil { 633 public := hs.cert.PrivateKey.(crypto.Signer).Public() 634 if rsaKey, ok := public.(*rsa.PublicKey); ok && sigType == signatureRSAPSS && 635 rsaKey.N.BitLen()/8 < sigHash.Size()*2+2 { // key too small for RSA-PSS 636 c.sendAlert(alertHandshakeFailure) 637 } else { 638 c.sendAlert(alertInternalError) 639 } 640 return errors.New("tls: failed to sign handshake: " + err.Error()) 641 } 642 certVerifyMsg.signature = sig 643 644 hs.transcript.Write(certVerifyMsg.marshal()) 645 if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil { 646 return err 647 } 648 649 return nil 650 } 651 652 func (hs *serverHandshakeStateTLS13) sendServerFinished() error { 653 c := hs.c 654 655 finished := &finishedMsg{ 656 verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript), 657 } 658 659 hs.transcript.Write(finished.marshal()) 660 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil { 661 return err 662 } 663 664 // Derive secrets that take context through the server Finished. 665 666 hs.masterSecret = hs.suite.extract(nil, 667 hs.suite.deriveSecret(hs.handshakeSecret, "derived", nil)) 668 669 hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret, 670 clientApplicationTrafficLabel, hs.transcript) 671 serverSecret := hs.suite.deriveSecret(hs.masterSecret, 672 serverApplicationTrafficLabel, hs.transcript) 673 c.out.setTrafficSecret(hs.suite, serverSecret) 674 675 err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret) 676 if err != nil { 677 c.sendAlert(alertInternalError) 678 return err 679 } 680 err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.clientHello.random, serverSecret) 681 if err != nil { 682 c.sendAlert(alertInternalError) 683 return err 684 } 685 686 c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript) 687 688 // If we did not request client certificates, at this point we can 689 // precompute the client finished and roll the transcript forward to send 690 // session tickets in our first flight. 691 if !hs.requestClientCert() { 692 if err := hs.sendSessionTickets(); err != nil { 693 return err 694 } 695 } 696 697 return nil 698 } 699 700 func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool { 701 if hs.c.config.SessionTicketsDisabled { 702 return false 703 } 704 705 // Don't send tickets the client wouldn't use. See RFC 8446, Section 4.2.9. 706 for _, pskMode := range hs.clientHello.pskModes { 707 if pskMode == pskModeDHE { 708 return true 709 } 710 } 711 return false 712 } 713 714 func (hs *serverHandshakeStateTLS13) sendSessionTickets() error { 715 c := hs.c 716 717 hs.clientFinished = hs.suite.finishedHash(c.in.trafficSecret, hs.transcript) 718 finishedMsg := &finishedMsg{ 719 verifyData: hs.clientFinished, 720 } 721 hs.transcript.Write(finishedMsg.marshal()) 722 723 if !hs.shouldSendSessionTickets() { 724 return nil 725 } 726 727 resumptionSecret := hs.suite.deriveSecret(hs.masterSecret, 728 resumptionLabel, hs.transcript) 729 730 m := new(newSessionTicketMsgTLS13) 731 732 var certsFromClient [][]byte 733 for _, cert := range c.peerCertificates { 734 certsFromClient = append(certsFromClient, cert.Raw) 735 } 736 state := sessionStateTLS13{ 737 cipherSuite: hs.suite.id, 738 createdAt: uint64(c.config.time().Unix()), 739 resumptionSecret: resumptionSecret, 740 certificate: Certificate{ 741 Certificate: certsFromClient, 742 OCSPStaple: c.ocspResponse, 743 SignedCertificateTimestamps: c.scts, 744 }, 745 } 746 var err error 747 m.label, err = c.encryptTicket(state.marshal()) 748 if err != nil { 749 return err 750 } 751 m.lifetime = uint32(maxSessionTicketLifetime / time.Second) 752 753 // ticket_age_add is a random 32-bit value. See RFC 8446, section 4.6.1 754 // The value is not stored anywhere; we never need to check the ticket age 755 // because 0-RTT is not supported. 756 ageAdd := make([]byte, 4) 757 _, err = hs.c.config.rand().Read(ageAdd) 758 if err != nil { 759 return err 760 } 761 m.ageAdd = binary.LittleEndian.Uint32(ageAdd) 762 763 // ticket_nonce, which must be unique per connection, is always left at 764 // zero because we only ever send one ticket per connection. 765 766 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil { 767 return err 768 } 769 770 return nil 771 } 772 773 func (hs *serverHandshakeStateTLS13) readClientCertificate() error { 774 c := hs.c 775 776 if !hs.requestClientCert() { 777 // Make sure the connection is still being verified whether or not 778 // the server requested a client certificate. 779 if c.config.VerifyConnection != nil { 780 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { 781 c.sendAlert(alertBadCertificate) 782 return err 783 } 784 } 785 return nil 786 } 787 788 // If we requested a client certificate, then the client must send a 789 // certificate message. If it's empty, no CertificateVerify is sent. 790 791 msg, err := c.readHandshake() 792 if err != nil { 793 return err 794 } 795 796 certMsg, ok := msg.(*certificateMsgTLS13) 797 if !ok { 798 c.sendAlert(alertUnexpectedMessage) 799 return unexpectedMessageError(certMsg, msg) 800 } 801 hs.transcript.Write(certMsg.marshal()) 802 803 if err := c.processCertsFromClient(certMsg.certificate); err != nil { 804 return err 805 } 806 807 if c.config.VerifyConnection != nil { 808 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { 809 c.sendAlert(alertBadCertificate) 810 return err 811 } 812 } 813 814 if len(certMsg.certificate.Certificate) != 0 { 815 msg, err = c.readHandshake() 816 if err != nil { 817 return err 818 } 819 820 certVerify, ok := msg.(*certificateVerifyMsg) 821 if !ok { 822 c.sendAlert(alertUnexpectedMessage) 823 return unexpectedMessageError(certVerify, msg) 824 } 825 826 // See RFC 8446, Section 4.4.3. 827 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) { 828 c.sendAlert(alertIllegalParameter) 829 return errors.New("tls: client certificate used with invalid signature algorithm") 830 } 831 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm) 832 if err != nil { 833 return c.sendAlert(alertInternalError) 834 } 835 if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 { 836 c.sendAlert(alertIllegalParameter) 837 return errors.New("tls: client certificate used with invalid signature algorithm") 838 } 839 signed := signedMessage(sigHash, clientSignatureContext, hs.transcript) 840 if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey, 841 sigHash, signed, certVerify.signature); err != nil { 842 c.sendAlert(alertDecryptError) 843 return errors.New("tls: invalid signature by the client certificate: " + err.Error()) 844 } 845 846 hs.transcript.Write(certVerify.marshal()) 847 } 848 849 // If we waited until the client certificates to send session tickets, we 850 // are ready to do it now. 851 if err := hs.sendSessionTickets(); err != nil { 852 return err 853 } 854 855 return nil 856 } 857 858 func (hs *serverHandshakeStateTLS13) readClientFinished() error { 859 c := hs.c 860 861 msg, err := c.readHandshake() 862 if err != nil { 863 return err 864 } 865 866 finished, ok := msg.(*finishedMsg) 867 if !ok { 868 c.sendAlert(alertUnexpectedMessage) 869 return unexpectedMessageError(finished, msg) 870 } 871 872 if !hmac.Equal(hs.clientFinished, finished.verifyData) { 873 c.sendAlert(alertDecryptError) 874 return errors.New("tls: invalid client finished hash") 875 } 876 877 c.in.setTrafficSecret(hs.suite, hs.trafficSecret) 878 879 return nil 880 }