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